Would you suggest a better (briefer or more legible) way of converting NULLs in a list to NAs; and from list to vector?
list(1, 2, 3, numeric(0), 5) %>%
purrr::map_dbl(~ ifelse(length(.) == 0, NA_real_, .))
# [1] 1 2 3 NA 5
I would prefer not using ifelse
and instead using if_else
.
Is there another way of doing it with purrr?
CodePudding user response:
If the length of each element of a list is 0 or 1 (e.g. lst.1
), you could simply use
lst.1 %>% map_dbl(1, .default = NA)
# [1] 1 2 3 NA 5
A general way to deal with a list with different length in each element (e.g. lst.2
) is
lst.2 %>%
map_if(~ length(.) == 0, ~ NA) %>%
flatten_dbl()
# [1] 1 2 3 NA 5
Data
lst.1 <- list(1, 2, 3, numeric(0), 5)
lst.2 <- list(1:3, numeric(0), 5)
CodePudding user response:
If L is the list then any of these work:
replace(L, lengths(L) == 0, NA)
ifelse(lengths(L), L, NA)
No packages needed.