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
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)
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
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.