Reputation: 2022
I am trying to replace the NULL elements of the list below with NAs inside a map() before using rbindlist on the cleaned list:
m = list(min = list(id = "min", val = NULL),
max = list(id = "max", val = 7),
split = list(id = "split", val = "gini"))
str(m)
List of 3
$ min :List of 2
..$ id : chr "min"
..$ val: NULL
$ max :List of 2
..$ id : chr "max"
..$ val: num 7
$ split:List of 2
..$ id : chr "split"
..$ val: chr "gini"
I have tried: map(m, ~list_modify(.x, new = 8), .default = NA) %>% rbindlist
but I'm not quite sure why the .default = NA
does not work. From the example in the documentation, I'm guessing it's because .default = NA
checks for NULLs at the first level of list returned by list_modify? Placing it inside list_modify()
did not work either. Is there a way to replace the NULLs with NA inside the map pipeline itself without the use of lapply?
Upvotes: 8
Views: 2284
Reputation: 6165
Using purrr::map_depth
, you can specify the depth at which values are to be replacd:
m = list(min = list(id = "min", val = NULL),
max = list(id = "max", val = 7),
split = list(id = "split", val = "gini"))
res <- purrr::map_depth(m, 2, ~ifelse(is.null(.x), NA, .x) )
str(res)
#> List of 3
#> $ min :List of 2
#> ..$ id : chr "min"
#> ..$ val: logi NA
#> $ max :List of 2
#> ..$ id : chr "max"
#> ..$ val: num 7
#> $ split:List of 2
#> ..$ id : chr "split"
#> ..$ val: chr "gini"
Created on 2021-10-18 by the reprex package (v2.0.1)
Upvotes: 5