在R中,如何通过分组变量折叠数据帧中的字符串变量?换句话说,垂直粘贴而不是水平粘贴

在R中,如何通过分组变量折叠数据帧中的字符串变量?换句话说,垂直粘贴而不是水平粘贴,r,string,collapse,dplyr,R,String,Collapse,Dplyr,我有以下示例数据框: model <- c(1,1,1,1,2,2,3,3,3) variable <- letters[seq(1:9)] df <- data.frame(model , variable) model variable 1 1 a 2 1 b 3 1 c 4 1 d 5 2 e 6 2 f 7 3

我有以下示例数据框:

model <- c(1,1,1,1,2,2,3,3,3)

variable <- letters[seq(1:9)]

df <- data.frame(model , variable)

  model variable
1     1        a
2     1        b
3     1        c
4     1        d
5     2        e
6     2        f
7     3        g
8     3        h
9     3        i

您可以使用聚合:

aggregate(variable ~ model, df, paste, collapse = " ")
#   model variable
# 1     1  a b c d
# 2     2      e f
# 3     3    g h i

…或
dcast
来自
reformae2
软件包:

> reshape2::dcast(df, model~., value.var = "variable", fun.aggregate = paste,
                  collapse = " ")
  model       .
1     1 a b c d
2     2     e f
3     3   g h i

或使用
data.table

 library(data.table)
 setDT(df)[,  list(variable=paste(variable, collapse=' ')), by=model]
 #   model variable
 #1:     1  a b c d
 #2:     2      e f
 #3:     3    g h i

如果您希望折叠多个不同的列,请参见“谢谢”!!!是否有可能在同一聚合函数中折叠多个字符字段?如果不是,这就足够棒了@Illya Big在这种情况下的预期输出是什么?@Illya Big你有没有费心去查看我评论中的链接?谢谢。这也很好。
 library(data.table)
 setDT(df)[,  list(variable=paste(variable, collapse=' ')), by=model]
 #   model variable
 #1:     1  a b c d
 #2:     2      e f
 #3:     3    g h i