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

大憨熊 提交于 2019-12-28 03:04:25

问题


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 expected because this is really a common task in data preprocessing. Thank you.

Here simplest means as.data.frame(aa) if it works. So one function from the base package of R will be great. sapply(aa, "length<-", max(lengths(aa))) has four functions actually.

An example is shown below.

Input:

aa <- list(A=c(1, 3, 4), B=c(3,5,7,7,8))

Output:

A B
1 3
3 5
4 7
NA 7
NA 8

A and B are the colnames of the data.frame.

One answer is sapply(aa, '[', seq(max(sapply(aa, length)))), but it's also complex.

ref:

  1. How to convert a list consisting of vector of different lengths to a usable data frame in R?

  2. Combining (cbind) vectors of different length


回答1:


We can use

data.frame(lapply(aa, "length<-", max(lengths(aa))))



回答2:


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



回答3:


Make this function:

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

Then use it, simply:

listToDF(aa)


来源:https://stackoverflow.com/questions/33613337/the-simplest-way-to-convert-a-list-with-various-length-vectors-to-a-data-frame-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!