Transform dataframe by grouping row

前端 未结 3 1620
深忆病人
深忆病人 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: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.

提交回复
热议问题