通过R中的一个组,在一列内有效地并发角色内容 [英] Efficiently concate character content within one column, by group in R

查看:125
本文介绍了通过R中的一个组,在一列内有效地并发角色内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the fastest way to perform concate-like operation over a data.frame in R? Suppose I have the following table:

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)

我想将内容列中的单元格的内容按组合有效地并入,以获得等同于:

I want to concate the content of cells in content column, by groups, efficiently, to receive the equivalent to:

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

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

我宁愿一些 dplyr 操作,但是不知道如何应用它。

I would prefer some dplyr operation, but have no good idea how to apply it.

推荐答案

这是一个使用基础的自定义的方法

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

(额外的g1 / g2 data.frame的rownames)

(the extra "g1/g2"s are the rownames of the data.frame)

这篇关于通过R中的一个组,在一列内有效地并发角色内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆