Convert R list to dataframe with missing/NULL elements

后端 未结 2 1501
生来不讨喜
生来不讨喜 2020-12-09 10:21

Given a list:

alist = list(
  list(name=\"Foo\",age=22),
  list(name=\"Bar\"),
  list(name=\"Baz\",age=NULL)
 )

what\'s the best way to con

相关标签:
2条回答
  • 2020-12-09 10:51

    A comment mentioned wanting only a single loop, which can be achieved with @flodel's answer just by putting the body of the two loops together:

    rbind.fill(lapply(alist, function(f) {
      as.data.frame(Filter(Negate(is.null), f))
    }))
    

    giving

      name age
    1  Foo  22
    2  Bar  NA
    3  Baz  NA
    
    0 讨论(0)
  • 2020-12-09 11:01

    Step1: remove NULL items

    non.null.list <- lapply(alist, Filter, f = Negate(is.null))
    

    Step2: stack everything together:

    library(plyr)
    rbind.fill(lapply(non.null.list, as.data.frame))
    #   name age
    # 1  Foo  22
    # 2  Bar  NA
    # 3  Baz  NA
    

    Edit: In case you had a variable that is NULL for all your list items, it would not show up in your final output. If instead, you'd like a column filled with NA, the first step should not remove NULLs but replace them with NAs:

    Step 1 alternative: replace NULL with NA:

    non.null.list <- lapply(alist, lapply, function(x)ifelse(is.null(x), NA, x))
    
    0 讨论(0)
提交回复
热议问题