temor
temor

Reputation: 1029

Replace null in a list in R?

I have a list that looks like:

  > str(gf)
       List of 28
         $ : NULL
         $ :'data.frame':       1 obs. of  2 variables:
               ..$ x: logi NA
               ..$ y: logi NA
         $ : NULL
         $ : NULL
         $ : NULL

I would like to replace all NULL with

                  data.frame(x=NA,y=NA)

Upvotes: 0

Views: 1735

Answers (1)

Roman
Roman

Reputation: 17668

You can try a tidyverse solution

library(tidyverse)
# a list
a <- list(NULL, data.frame(x=T, y=F), NULL)
str(a)
List of 3
 $ : NULL
 $ :'data.frame':   1 obs. of  2 variables:
  ..$ x: logi TRUE
  ..$ y: logi FALSE
 $ : NULL

# and replace 
modify_if(a, is.null, ~compact(a) %>% unlist())
[[1]]
    x     y 
 TRUE FALSE 

[[2]]
     x     y
1 TRUE FALSE

[[3]]
    x     y 
 TRUE FALSE 

# or
modify_if(a, is.null, ~data.frame(x=NA,y=NA))

Upvotes: 3

Related Questions