Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 595
Amnor Avatar asked Dec 14 '22 06:12

Amnor


2 Answers

Using base is simplest:

aggregate(df$Value~df$Type,FUN=c)

  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.

like image 156
Zahiro Mor Avatar answered Dec 16 '22 18:12

Zahiro Mor


We could use aggregate from base R

aggregate(Value~., df1, FUN= toString)
#   Type      Value
#1    A 12, 14, 13
#2    B     20, 15
like image 41
akrun Avatar answered Dec 16 '22 19:12

akrun