Clean a list of lists from GoogleSheets in R

Viewed 47

I have retrieved a sheet from google sheets and returned me a list of lists:

sheet <- list(var1 = list(Sys.time(), Sys.time(),NULL),
             var2 = list(NULL,1,2),
             var3 = list("a",NULL,"b"))

I have to convert all members of the list that are NULL into NAs. I was kindly explained how to do it list by list using for example sheet$var1[sapply(sheet$var1,is.null)] <- NA, but since I have many variables, is it possible to code it in just one line? Any help will be greatly appreciated.

1 Answers

It is a nested list. So we can do

library(purrr)
map(sheet, ~ map(.x, ~ replace(.x, is.null(.x), NA)))

Or with base R

lapply(sheet, function(x) lapply(x, function(y) replace(y, is.null(y), NA)))
#$var1
#$var1[[1]]
#[1] "2020-09-13 16:44:56 CDT"

#$var1[[2]]
#[1] "2020-09-13 16:44:56 CDT"

#$var1[[3]]
#[1] NA


#$var2
#$var2[[1]]
#[1] NA

#$var2[[2]]
#[1] 1

#$var2[[3]]
#[1] 2


#$var3
#$var3[[1]]
#[1] "a"

#$var3[[2]]
#[1] NA

#$var3[[3]]
#[1] "b"

Or do this recursively with rrapply

library(rrapply)
rrapply(sheet, f = function(x) replace(x, is.null(x), NA), how = "list")
Related