如何轻松安全地重塑R中的数据?

时间:2014-02-28 12:25:33

标签: r reshape

我经常以“宽格式”生成数据,其中包含同一变量的多个列(请参阅here),我希望以长格式显示数据(请参阅here) 。您有任何简单安全的解决方案吗?

2 个答案:

答案 0 :(得分:1)

由于您的2个示例没有相同的数字,因此不知道这是否是您想要的:

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'))

答案 1 :(得分:0)

或者使用熔化功能进行钝化:

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")