0

I have a data frame which looks like this:

ID    Age
1     19
2     20
3     56
4     81

I want to add up the column age and comma delimit ID:

ID         Age
1,2,3,4    176

I have tried this:

aggregate(ID ~., data, toString) as per this solution:

Collapse / concatenate / aggregate a column to a single comma separated string within each group

But, this is not producing desired result.

Axeman
  • 32,068
  • 8
  • 81
  • 94
J Doe
  • 317
  • 1
  • 4
  • 12

2 Answers2

3

You can make a new data frame by applying different functions to each column.

#Your data
df <- data.frame(ID = c(1:4),
                 Age = c(19,20,56,81))
#Output
resul <- data.frame(ID = paste(df$ID, collapse = ","),
                    Age = sum(df$Age))

#       ID Age
#1 1,2,3,4 176
0

We can use dplyr

library(dplyr)
df %>% summarise(ID = toString(ID), Age = sum(Age))

#          ID Age
#1 1, 2, 3, 4 176

and data.table

library(data.table)
setDT(df)[, .(ID = toString(ID), Age = sum(Age))]
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213