2014-02-28 68 views

回答

1

當你的兩個例子不具有相同的數字,不知道這是否是你想要什麼:

data <- read.table(text='"id","name1","name2","x1","x2" 
1,"Mr a","Mr c","0.575710014459387","-0.991747242336918" 
2,"Mr b","Mr d","-0.126033858727122","0.854792650572792"', sep=',', header=TRUE) 

reshape(data, direction = 'long', idvar = 'id', varying = list(c('x1', 'x2'), c('name1', 'name2')), times=c('a', 'b')) 
0

或者與熔體功能UNPIVOT:

library(reshape2) 
data <- read.table(text='"id","name1","name2","x1","x2","Mr a","Mr c","0.575710014459387","-0.991747242336918","Mr b","Mr d","-0.126033858727122","0.854792650572792"', sep=',', header=TRUE) 
reshape(data, direction = 'long', idvar = 'id', varying = list(c('x1', 'x2'), c('name1', 'name2')), times=c('a', 'b')) 
melt(data,c("id","name1","name2"),variable.name="x",value.name="value")