简体   繁体   中英

R - Using purrr to replace NULL elements with NA in a list of lists

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?

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM