我想重塑数据框架。
数据:
a <- c("A_h:old","A_h:new","A_h:old","A_h:new","A_h:old","A_h:new","A_h:old","A_h:new")
b <- c("2015-08-11","2015-08-11","2015-08-12","2015-08-12","2015-08-13","2015-08-13","2015-08-14","2015-08-14")
c <- c(12,10,12,23,16,17,7,9)
df <- data.frame(a,b,c)
产生:
a b c
A_h:old 2015-08-11 12
B_h:new 2015-08-11 10
A_h:old 2015-08-12 12
B_h:new 2015-08-12 23
A_h:old 2015-08-13 16
B_h:new 2015-08-13 17
A_h:old 2015-08-14 7
B_h:new 2015-08-14 9
期望的结果:
b A_h:old B_h:new
2015-08-11 12 10
2015-08-12 12 23
2015-08-13 16 17
2015-08-14 7 9
我试图使用:
reshape(df, timevar = "b", idvar = c(" A_h:old", "B_h:new"), direction = "wide")
失败。
答案 0 :(得分:0)
我们可以使用dcast
中的reshape2
将'long'转换为'wide'
library(reshape2)
dcast(df, b~a, value.var='c')
# b A_h:new A_h:old
#1 2015-08-11 10 12
#2 2015-08-12 23 12
#3 2015-08-13 17 16
#4 2015-08-14 9 7