r - grouped data frame to list -


i've got data frame contains names grouped, so:

df <- data.frame(group = rep(letters[1:2], each=2),                  name = letters[1:4]) > df   group name 1        2        b 3     b    c 4     b    d 

i convert list keyed on group names , contains names. example output:

df_out <- list(a=c('a', 'b'),                b=c('c', 'd'))  > df_out $a [1] "a" "b"  $b [1] "c" "d" 

this not new question wholly within tidyverse.

there no such function yet in tidyverse far know. thus, have write own:

split_tibble <- function(tibble, col = 'col') tibble %>% split(., .[,col]) 

then:

dflist <- split_tibble(df, 'group') 

results in alist of dataframes:

> dflist $a   group name 1        2        b  $b   group name 3     b    c 4     b    d  > sapply(dflist, class)                       b  "data.frame" "data.frame"  

to desired output, you'll have extend function bit:

split_tibble <- function(tibble, column = 'col') {   tibble %>% split(., .[,column]) %>% lapply(., function(x) x[,setdiff(names(x),column)]) } 

now:

split_tibble(df, 'group') 

results in:

$a [1] b levels: b c d  $b [1] c d levels: b c d 

considering alternatives in comments , both answers, leads following conclusion: using base r alternative split(df$name, df$group) wiser.


Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -