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

前端 未结 3 1024
眼角桃花
眼角桃花 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:00

    Make this function:

    listToDF <- function(aa){
      sapply(aa, "length<-", max(lengths(aa)))
     }
    

    Then use it, simply:

    listToDF(aa)
    
    0 讨论(0)
  • 2020-12-01 21:19

    We can use

    data.frame(lapply(aa, "length<-", max(lengths(aa))))
    
    0 讨论(0)
  • 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
        * <int> <dbl> <dbl>
        1     1     1     3
        2     2     3     5
        3     3     4     7
        4     4    NA     7
        5     5    NA     8
    
    0 讨论(0)
提交回复
热议问题