使用此示例变量
df <- data.frame(month=rep(1:3,2),
student=rep(c("Amy", "Bob"), each=3),
A=c(9, 7, 6, 8, 6, 9),
B=c(6, 7, 8, 5, 6, 7))
我可以使用tidyr
中的spread
函数,将此数据转换为宽格式。
> df[, -4] %>% spread(student, A)
month Amy Bob
1 1 9 8
2 2 7 6
3 3 6 9
但是我该如何传播两个值,例如 A
和 B
,以便输出为以下内容:
month Amy.A Bob.A Amy.B Bob.B
1 1 9 8 6 5
2 2 7 6 7 6
3 3 6 9 8 7
data.table
解决方案,并将fun.aggregate = sum
添加到dcast
中。 - David Arenburgspread
和gather
并不适用于应用函数。你可能需要使用dplyr
。或者,你可以像我之前建议的那样使用dcast
。如果你对此有强烈的感觉,也可以发布一个新问题。 - David Arenburgpivot_wider(data = df, id_cols = month, names_from = student, values_from = c("A", "B"))
应该可以在 tidyr 1.0.0 或以上的版本中使用。 - guyabel