R:转换数据(因子值作为列名)

时间:2014-12-11 15:40:53

标签: r transform

我有一个我想要转换成另一种格式的数据集:

数据看起来像这样(出于隐私问题,我无法提供原始数据):

ID1 ID2 Month   Value
1   A   Jan-03  10
2   B   Jan-03  11
1   A   Feb-03  12
2   B   Feb-03  13
1   A   Mar-03  14
2   B   Mar-03  15

我希望Month列作为列名,格式如下:

ID1 ID2 Jan-03  Feb-03  Mar-03
1   A   10  12  14
2   B   11  13  16

谢谢!

1 个答案:

答案 0 :(得分:5)

你可以尝试

 df$Month <- factor(df$Month, levels=unique(df$Month))
 reshape(df, idvar=c('ID1', 'ID2'), timevar='Month', direction='wide')
 #  ID1 ID2 Value.Jan-03 Value.Feb-03 Value.Mar-03
 #1   1   A           10           12           14
 #2   2   B           11           13           15

或者

library(reshape2)
dcast(df, ID1+ID2~Month, value.var='Value')
#   ID1 ID2 Jan-03 Feb-03 Mar-03
#1   1   A     10     12     14
#2   2   B     11     13     15

或者

library(tidyr)
spread(df, Month, Value)
#   ID1 ID2 Jan-03 Feb-03 Mar-03
#1   1   A     10     12     14
#2   2   B     11     13     15

数据

df <- structure(list(ID1 = c(1L, 2L, 1L, 2L, 1L, 2L), ID2 = c("A", 
"B", "A", "B", "A", "B"), Month = c("Jan-03", "Jan-03", "Feb-03", 
"Feb-03", "Mar-03", "Mar-03"), Value = 10:15), .Names = c("ID1", 
"ID2", "Month", "Value"), class = "data.frame", row.names = c(NA, 
-6L))