R用tidyr传播多个列

R用tidyr传播多个列

拿这个样本变量


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))

我可以使用spread从tidyr将其更改为宽格式。


> 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


天涯尽头无女友
浏览 424回答 1
1回答

潇潇雨雨

这是一个简单而有效的解决方案 data.tablelibrary(data.table) ## v >= 1.9.6dcast(setDT(df), month ~ student, value.var = c("A", "B"))&nbsp;#&nbsp; &nbsp; month Amy_A Bob_A Amy_B Bob_B# 1:&nbsp; &nbsp; &nbsp;1&nbsp; &nbsp; &nbsp;9&nbsp; &nbsp; &nbsp;8&nbsp; &nbsp; &nbsp;6&nbsp; &nbsp; &nbsp;5# 2:&nbsp; &nbsp; &nbsp;2&nbsp; &nbsp; &nbsp;7&nbsp; &nbsp; &nbsp;6&nbsp; &nbsp; &nbsp;7&nbsp; &nbsp; &nbsp;6# 3:&nbsp; &nbsp; &nbsp;3&nbsp; &nbsp; &nbsp;6&nbsp; &nbsp; &nbsp;9&nbsp; &nbsp; &nbsp;8&nbsp; &nbsp; &nbsp;7或者可能的tidyr解决方案df %>%&nbsp;&nbsp; gather(variable, value, -(month:student)) %>%&nbsp; unite(temp, student, variable) %>%&nbsp; spread(temp, value)#&nbsp; &nbsp;month Amy_A Amy_B Bob_A Bob_B# 1&nbsp; &nbsp; &nbsp;1&nbsp; &nbsp; &nbsp;9&nbsp; &nbsp; &nbsp;6&nbsp; &nbsp; &nbsp;8&nbsp; &nbsp; &nbsp;5# 2&nbsp; &nbsp; &nbsp;2&nbsp; &nbsp; &nbsp;7&nbsp; &nbsp; &nbsp;7&nbsp; &nbsp; &nbsp;6&nbsp; &nbsp; &nbsp;6# 3&nbsp; &nbsp; &nbsp;3&nbsp; &nbsp; &nbsp;6&nbsp; &nbsp; &nbsp;8&nbsp; &nbsp; &nbsp;9&nbsp; &nbsp; &nbsp;7
打开App,查看更多内容
随时随地看视频慕课网APP