通过匹配元素缩小数据框行

时间:2018-08-08 09:06:31

标签: r

我有一个看起来像这样的数据框:

  Name   Desc    Sex
1 John   young   M
2 Diana  young   F
3 Bob    old     M
4 Hanna  young   F
5 Ben    old     M
6 Liza   old     F
7 Ron    young   M

有没有一种方法可以对行进行分组,使其以以下数据帧结尾?

  Name          Desc   Sex
1 John, Ron     young  M
2 Diana, Hanna  young  F
3 Bob, Ben      old    M
4 Liza          old    F

数据

df <- read.table(text="Name   Desc    Sex
1 John   young   M
2 Diana  young   F
3 Bob    old     M
4 Hanna  young   F
5 Ben    old     M
6 Liza   old     F
7 Ron    young   M",h=T,strin=F)

3 个答案:

答案 0 :(得分:4)

使用dplyr我们可以做到

library(dplyr)
df %>% group_by(Desc,Sex) %>% summarise(Name=paste(Name,collapse = ','))

# A tibble: 4 x 3
# Groups:   Desc [2]
  Desc  Sex   Name       
 <fct> <fct> <chr>      
1 old   F     Liza       
2 old   M     Bob,Ben    
3 young F     Diana,Hanna
4 young M     John,Ron   

答案 1 :(得分:1)

您可以在基础aggregate中使用R

aggregate(Name ~ ., df, paste, collapse= ", ")
#    Desc Sex         Name
# 1   old   F         Liza
# 2 young   F Diana, Hanna
# 3   old   M     Bob, Ben
# 4 young   M    John, Ron

答案 2 :(得分:1)

我们可以使用data.table。将'data.frame'转换为'data.table'(setDT(df)),按'Desc','Sex'paste'Name'分组,并以,

library(data.table)
setDT(df)[, .(Name = toString(Name)), by = .(Desc, Sex)]
#    Desc Sex         Name
#1: young   M    John, Ron
#2: young   F Diana, Hanna
#3:   old   M     Bob, Ben
#4:   old   F         Liza