按变量分组并合并另一列中的行数据 [英] Group by a variable and merge row data from another column

查看:44
本文介绍了按变量分组并合并另一列中的行数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按一列对数据进行分组,然后将另一列中的字符串粘贴到一行中.例如,假设我有一个 data.frame A :

I want to group my data by one column and paste the character strings from a different column into a single row. Suppose, for example, I have a data.frame A:

library(dplyr)
A <- data.frame(student = rep(c("John Smith", "Jane Smith"), 3),
                variable1 = rep(c("Var1", "Var1", "Var2"), 2))
    A <- arrange(A, student)

     student variable1
1 Jane Smith      Var1
2 Jane Smith      Var1
3 Jane Smith      Var2
4 John Smith      Var1
5 John Smith      Var2
6 John Smith      Var1

但是,我需要将 data.frame A 转换为 data.frame B ,按 student 变量,并将 variable1 的所有变体粘贴到一起:

But, I need to transform data.frame A into data.frame B, grouped by the student variable and pasting any variations from variable1 together:

B <- data.frame(student = c("John Smith", "Jane Smith"), 
                variable1 = c(paste("Var1", "Var2", sep = ","),     
                              paste("Var1", "Var2", sep = ",")))

     student variable1
1 John Smith Var1,Var2
2 Jane Smith Var1,Var2

我已经尝试过 dplyr 包中的许多 group_by mutate 子句,但是都没有成功.

I've attempted numerous group_by and mutate clauses from the dplyr package but haven't found success.

推荐答案

我相信您可以使用聚合函数来完成所需的工作.这是您想要做的吗?

I believe you can use the aggregate function to do what you are looking for. Is this what you are trying to do?

df=unique(A)
agg=aggregate(df$variable1, list(df$student), paste, collapse=",")

> agg
             Group.1         x
        1 Jane Smith Var1,Var2
        2 John Smith Var1,Var2

这篇关于按变量分组并合并另一列中的行数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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