Convert list with NULL entres to data.frame in R

前端 未结 3 726
说谎
说谎 2021-01-14 11:32

I have a list named z :

z<-list( list(a=1, b=2),  list(a=2, b=3), list(a=NULL, b=4))

I want this to be converted to a data.

相关标签:
3条回答
  • 2021-01-14 12:16

    If you're interested in data frame of numeric values instead of data frame of lists, you can try the below.

    lz <- lapply(z, function(x) {
        nonnull <- sapply(x, typeof)!="NULL"
        do.call(data.frame, c(x[nonnull], stringsAsFactors=FALSE))
    })
    
    require(plyr)
    df <- ldply(lz)
    

    Note that the result will have NULLs converted to NAs to form valid dataframes.

    > df
       a b
    1  1 2
    2  2 3
    3 NA 4
    > str(df)
    'data.frame':   3 obs. of  2 variables:
     $ a: num  1 2 NA
     $ b: num  2 3 4
    
    0 讨论(0)
  • 2021-01-14 12:26
     as.data.frame(do.call(rbind, z))
         a b
    1    1 2
    2    2 3
    3 NULL 4
    
    0 讨论(0)
  • 2021-01-14 12:36

    Is this what you are trying to do?

    > data.frame(do.call(rbind, z))
         a b
    1    1 2
    2    2 3
    3 NULL 4
    
    0 讨论(0)
提交回复
热议问题