Amnor Amnor - 1 year ago 67
R Question

How to group in a row values of the same value in a column with R?

I'm tryng to sequence a dataset, and I'm a little lost with this. I have everything else done, data filtering, duplicated values eliminated, ordered by date... but im stuck with this, maybe one of the most simple parts. My goal is to convert this data frame:

Type Value
A 12
B 20
A 14
A 13
B 15

To something like this:

A 12,14,13
B 20,15

Any idea on how to do this?

Thanks in advance!

Answer Source

Using base is simplest:


  df$Type   df$Value
1       A 12, 14, 13
2       B     20, 15

using FUN=c keeps the Value type to numeric (actually a numeric vector) which is better imho than converting to String

however.... if no more transformations are needed and you want to save the above as CSV - you DO want to convert to String:

write.csv(x = aggregate(df$Value~df$Type,FUN=toString),file = "nameMe")

works fine.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download