通过R中的组有效地连接一列中的字符内容

时间:2014-07-03 16:01:37

标签: r dataframe concatenation aggregate dplyr

data.frame中的R执行类似连接操作的最快方法是什么?假设我有下表:

df <- data.frame(content = c("c1", "c2", "c3", "c4", "c5"),
                 groups = c("g1", "g1", "g1", "g2", "g2"),
                 stringsAsFactors = F)

df$groups <- as.factor(df$groups)

我希望有效地按组content列连接单元格的内容,以获得相当于:

df2 <- data.frame(content = c("c1 c2 c3", "c4 c5"),
                  groups = c("g1", "g2"),
                  stringsAsFactors = F)

df2 $groups <- as.factor(df2 $groups)

我更喜欢一些dplyr操作,但不知道如何应用它。

3 个答案:

答案 0 :(得分:3)

tapply的近似值为aggregate,可让您执行此操作:

aggregate(content ~ groups, df, paste, collapse = " ")
#   groups  content
# 1     g1 c1 c2 c3
# 2     g2    c4 c5

保留因素:

str(.Last.value)
# 'data.frame':  2 obs. of  2 variables:
#  $ groups : Factor w/ 2 levels "g1","g2": 1 2
#  $ content: chr  "c1 c2 c3" "c4 c5"

既然你提到你正在寻找dplyr方法,你可以尝试这样的事情:

library(dplyr)
df %>% group_by(groups) %>% summarise(content = paste(content, collapse = " "))
# Source: local data frame [2 x 2]
# 
#   groups  content
# 1     g1 c1 c2 c3
# 2     g2    c4 c5

答案 1 :(得分:2)

使用data.table

library(data.table)
dt = as.data.table(df)

dt[, paste(content, collapse = " "), by = groups]
#   groups       V1
#1:     g1 c1 c2 c3
#2:     g2    c4 c5

由于OP中提到了速度,data.tabledplyr非常接近(基本方法非常慢,测试它们没有意义):

dt = data.table(content = sample(letters, 26e6, T), groups = LETTERS)
df = as.data.frame(dt)

system.time(dt[, paste(content, collapse = " "), by = groups])
#   user  system elapsed 
#   5.37    0.06    5.65 

system.time(df %>% group_by(groups) %>% summarise(paste(content, collapse = " ")))
#   user  system elapsed 
#   7.10    0.13    7.67 

答案 2 :(得分:0)

以下是使用基础tapply

的方法
splat<-with(df, tapply(content, groups, paste, collapse=" "))
df2<-data.frame(groups=names(splat), content=splat, stringsAsFactors=F)
df2$groups <- as.factor(df2$groups)

给你

#    groups  content
# g1     g1 c1 c2 c3
# g2     g2    c4 c5

(额外&#34; g1 / g2&#34; s是data.frame的rownames)