I have a data frame below with common elements in colomn "id".
df<- data.frame(id=c("x1","x2","x3","x4","x5","x2"),figure=sample(1:5,6,replace=T))
id figure
x1 5
x2 5
x3 3
x4 2
x5 5
x2 2
I want to combine the rows with the same element as a list in the data frame so it would look something like this
id figure
x1 5
x2 c(2,5)
x3 3
x4 2
x5 5
The function you need is split:
split(df$figure,df$id)
The dplyr way.
df1 <- data.frame(id=c("x1","x2","x3","x4","x5","x2"),figure=sample(1:5,6,replace=T))
df1 %>% group_by(id) %>%
mutate(figure = as.character(figure),
figure = ifelse(length(figure)>=2,
paste(figure, collapse=" "), figure) ) %>%
unique
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With