Transform dataframe by grouping row

前端 未结 3 1616
深忆病人
深忆病人 2021-01-28 13:57

d1 <- data.frame(Gender=c(\'M\', \'M\', \'M\', \'M\', \'F\', \'F\', \'F\',\'F\'), Age=c(15,38,17,35,26,24,20,26))

And I\'d like to transform it to look l

相关标签:
3条回答
  • 2021-01-28 14:30

    You can split by gender, then combine into your string, and finally combine:

    spl = split(d1, d1$Gender)
    spl = lapply(spl, function(x) data.frame(Gender=x$Gender[1],
                                             Age=paste(x$Age, collapse=", ")))
    result = do.call(rbind, spl)
    
    0 讨论(0)
  • 2021-01-28 14:34

    I'll add the requisite plyr based solution:

    library("plyr")
    ddply(d1, .(Gender), summarize, Age = paste(Age, collapse = ", "))
    ##   Gender            Age
    ## 1      F 26, 24, 20, 26
    ## 2      M 15, 38, 17, 35
    
    0 讨论(0)
  • 2021-01-28 14:37

    If you just want to display this, and I would advise not to "transform it", you could do this:

     with(d1, aggregate(Age, list(Gender=Gender), list) )
      Gender              x
    1      F 26, 24, 20, 26
    2      M 15, 38, 17, 35
    

    I noticed that @Henrik deleted his answer that used aggregate.formula, perhaps because of my answer which would be unfortunate because I was going to delete mine in favor of his. This is what he wrote and I think it's better than mine:

    aggregate(Age ~ Gender, data = d1, function(x) paste(x, collapse = ", "))
    

    But be on notice that both this and the earlier accepted answer both return those Age variables as factors.

    0 讨论(0)
提交回复
热议问题