Unnest a list column directly into several columns

后端 未结 6 867
面向向阳花
面向向阳花 2020-12-05 23:33

Can I unnest a list column directly into n columns?

The list can be assumed to regular, with all elements being of equal length.

If instead of a lis

6条回答
  •  -上瘾入骨i
    2020-12-05 23:57

    Another one:

    library(tibble)
    library(dplyr)
    
    df1 <- data_frame(
      gr = c('a', 'b', 'c'),
      values = list(1:2, 3:4, 5:6)
    )
    
    df %>% mutate(V1 = sapply(values, "[[", 1), V2 = sapply(values, "[[", 2))
    
    # A tibble: 3 x 4
      gr    values       V1    V2
            
    1 a          1     2
    2 b          3     4
    3 c          5     6
    

    Edit:

    When the listed vectors are very long, and writing by hand V1 = sapply(values, "[[", index) is not convenient, then you can combine it with f_interp from lazyeval:

    library(tibble)
    library(dplyr)
    library(lazyeval)
    df <- data_frame(gr = c('a', 'b', 'c'), values = list(1:11, 3:13, 5:15))
    nums <- c(1:11)
    ll <- lapply(nums, function(nr) f_interp(~sapply(values, "[[", uq(nr))))
    mutate_(df, .dots=setNames(ll, paste("V", nums, sep="")))
    
    # A tibble: 3 x 12
      gr    values        V1    V2    V3    V4    V5    V6    V7    V8    V9   V10
                     
    1 a          1     2     3     4     5     6     7     8     9    10
    2 b          3     4     5     6     7     8     9    10    11    12
    3 c          5     6     7     8     9    10    11    12    13    14
    

提交回复
热议问题