Group by columns and summarize a column into a list

后端 未结 1 2006
感情败类
感情败类 2020-12-09 10:48

I have a dataframe like this:

sample_df<-data.frame(
   client=c(\'John\', \'John\',\'Mary\',\'Mary\'),
   date=c(\'2016-07-13\',\'2016-07-13\',\'2016-07         


        
相关标签:
1条回答
  • 2020-12-09 11:39

    We can use toString to concat the unique elements in 'cluster' together after grouping by 'client'

    r1 <- sample_df %>% 
             group_by(client, date) %>%
             summarise(cluster = toString(unique(cluster)))
    

    Or another option would be to create a list column

    r2 <- sample_df %>%
             group_by(client, date) %>% 
             summarise(cluster = list(unique(cluster)))
    

    which we can unnest

    library(tidyr)
    r2 %>%
        ungroup %>%
         unnest()
    
    0 讨论(0)
提交回复
热议问题