Cody
Cody

Reputation: 23

Creating a new variable by combining multiple rows from 1 column

I have a data frame with many columns.

This is what it currently looks like:

ID     Type
1       A
1       B
2       B
2       C
3       A
3       C

And this is what I want it to look like:

ID     Type
1      A&B
2      B&C
3      A&C

I would like to do this without disrupting the rest of the columns. So it's basically going from long to wide form, but just for that one column. Is that possible?

Upvotes: 1

Views: 64

Answers (1)

Joe
Joe

Reputation: 646

x <- data.frame(ID = c(1,1,2,2,3,3), type = c('A','B','B','C','A','C'))

library(dplyr)
x %>%
  group_by(ID) %>%
  summarise(y = paste(type,collapse="&"))

This is just one way, but it is certainly possible.

Upvotes: 5

Related Questions