I want to aggregate one column in a data frame according to two grouping variables, and separate the individual values by a comma.
Here is some data:
data <- data.frame(A = c(rep(111, 3), rep(222, 3)), B = rep(1:2, 3), C = c(5:10))
data
# A B C
# 1 111 1 5
# 2 111 2 6
# 3 111 1 7
# 4 222 2 8
# 5 222 1 9
# 6 222 2 10
"A" and "B" are grouping variables, and "C" is the variable that I want to collapse into a comma separated character
string. I have tried:
library(plyr)
ddply(data, .(A,B), summarise, test = list(C))
A B test
1 111 1 5, 7
2 111 2 6
3 222 1 9
4 222 2 8, 10
but when I tried to convert test column to character
it becomes like this:
ddply(data, .(A,B), summarise, test = as.character(list(C)))
# A B test
# 1 111 1 c(5, 7)
# 2 111 2 6
# 3 222 1 9
# 4 222 2 c(8, 10)
How can I keep the character
format and separate them by a comma? For example, row 1 should be only "5,7"
, and not as c(5,7).
Change where you put
as.character
:Note, however, that each item is still actually a separate character, not a single character string. That is, this is not an actual string that looks like "5, 7", but rather, two characters, "5" and "7", which R displays with a comma between them.
Compare with the following:
The comparable solution in base R is, of course,
aggregate
:plyr Try using
toString
:Here are some additional alternatives also using
toString
:data.table
aggregate This uses no packages:
sqldf
And here is an alternative using the SQL function
group_concat
using the sqldf package :dplyr A
dplyr
alternative: