The simplest way to convert a list with various length vectors to a data.frame in R

前端 未结 3 1042
眼角桃花
眼角桃花 2020-12-01 20:33

Here I have a list with different length vectors. And I\'d want to get a data.frame. I\'ve seen lots of posts about it in SO (see ref), but none of them are as simple as I e

3条回答
  •  独厮守ぢ
    2020-12-01 21:19

    Using tidyverse packages. Place the list in a nested data frame. Extract the name for each vector in the list. Unnest the data frame. Give a row index i for each element in each vector, spread the data in wide format

        aa <- list(A = c(1, 3, 4), B = c(3, 5, 7, 7, 8))
        library(tidyverse)
        data_frame(data = aa) %>% 
            group_by(name = names(data)) %>% 
            unnest() %>%
            mutate(i = row_number()) %>% 
            spread(name, data)
        # A tibble: 5 x 3
              i     A     B
        *   
        1     1     1     3
        2     2     3     5
        3     3     4     7
        4     4    NA     7
        5     5    NA     8
    

提交回复
热议问题