Reputation: 21
I'm new at R programing and Im trying to rearrange a data frame. Basically I have a column with IDs and a column with y string values. There's more than one y per ID so multiple rows with the same ID but different y. I want to get only one row per ID and all the y value concatenated in the same cell in the other column. Is there a function that does that ?
original data
ID y
A apple
B pear
C grape
A grape
B apple
C grape
transformed data
ID y
A apple,grape
B pear, apple
C grape
Upvotes: 2
Views: 2031
Reputation: 25854
You can use aggregate()
here to paste()
the unique()
elements for each ID
together
aggregate(y ~ ID, unique(dat), paste, collapse = ", ")
data
dat <- read.table(text="ID y
A apple
B pear
C grape
A grape
B apple
C grape", header=T)
EDIT added collapse
argument re @pdb comment and changed unique
re @DavidArenburg
Upvotes: 5