使用
df <- data.frame(id=rep(1:2, rep(6,2)), treat=rep(rep(101:102, c(3,3)),2),
flavor=c(13,7,28,15,5,21,32,14,27,24,15,17))
df
id treat flavor
1 1 101 13
2 1 101 7
3 1 101 28
4 1 102 15
5 1 102 5
6 1 102 21
7 2 101 32
8 2 101 14
9 2 101 27
10 2 102 24
11 2 102 15
12 2 102 17
我已经融化了数据:
df.melt <- melt(df, measure.var = "flavor")
df.melt
id treat variable value
1 1 101 flavor 13
2 1 101 flavor 7
3 1 101 flavor 28
4 1 102 flavor 15
5 1 102 flavor 5
6 1 102 flavor 21
7 2 101 flavor 32
8 2 101 flavor 14
9 2 101 flavor 27
10 2 102 flavor 24
11 2 102 flavor 15
12 2 102 flavor 17
要投射df.melt
,我需要的结果如下所示,变量flavor
总结为每个id
,但也会根据treat
的每种类型进行总结,但转换到列:
df.cast
id flavor_total treat_101 treat_102
1 1 89 48 41
2 2 129 73 56
这可以用cast
执行此操作吗?
答案 0 :(得分:1)
如果你想使用演员表,也许这会有所帮助:
> dfmc <- cast( df.melt, id ~ treat, sum )
> dfmc
id 101 102
1 1 48 41
2 2 73 56
> dfmc$total <- rowSums( dfmc )
> dfmc
id 101 102 total
1 1 48 41 89
2 2 73 56 129