假设我有以下数据框:
df <- data.frame(id = c(1,1,1,2,2,3),
content = c("red", "yellow", "blue", "red", "black", "white"),
content2 = c("cat", "dog", "horse", "cat", "dog", "horse"))
我想创建一个数据框,其中包含与唯一ID值一样多的行,其他列在列表中折叠。
输出应如下所示:
output <- data.frame(id = c(1,2,3),
content = I(list(c("red", "yellow", "blue"), c("red", "black"), c("white", "black"))),
content2 = I(list(c("cat", "dog", "horse"), c("cat", "dog"), c("horse", "duck"))))
我还想知道如何再次走另一条路,从output
到df
。
答案 0 :(得分:2)
我们可以使用summarise_each
library(dplyr)
res <- df %>%
group_by(id) %>%
summarise_each(funs(list(.)))
返回原始数据集
library(tidyr)
unnest(res)