Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining Rows into List in R

Tags:

dataframe

r

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
like image 723
jbest Avatar asked Dec 06 '25 15:12

jbest


2 Answers

The function you need is split:

split(df$figure,df$id)
like image 62
Roman Avatar answered Dec 08 '25 04:12

Roman


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
like image 31
Ven Yao Avatar answered Dec 08 '25 03:12

Ven Yao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!