Reputation: 2977
With
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
I've molten the data:
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
To cast df.melt
, I need my result looks like the following with variable flavor
summed up for each id
but also summed up according to each type of treat
but transposed to the column:
df.cast
id flavor_total treat_101 treat_102
1 1 89 48 41
2 2 129 73 56
Is this possible to do this with cast
?
Upvotes: 0
Views: 299
Reputation: 7659
If you want to use cast, maybe this helps:
> 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
Upvotes: 1