-
Notifications
You must be signed in to change notification settings - Fork 276
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Allow map_* to treat NULLs as NAs #231
Comments
This ground has been explored some before (#110 Default value to replace NULL), which lead to the Does this help? library(purrr)
list(list("a" = 1L), list("b" = 2L)) %>% map_int("a", .null = NA_integer_)
#> [1] 1 NA |
I totally missed that (and this issue) - my apologies. I missed it in part because it's not in the parameters section of the documentation. Should it be added there? It is mentioned under the |
OK, so on further inspection, the list(list("a" = 1L), list("a" = NULL)) %>% map_int("a", .null = NA)
#> Error: Result 2 is not a length 1 atomic vector Reading through #110, it seems like the discussion lost the need to treat |
Good point about explicit |
I also think actual NULLs should be replaced by |
I always struggle with this one. stuff <- c(list("a"), list(NULL))
stuff |> purrr::map_chr(as.character, .null=NA_character_)
#> Error in `stop_bad_type()`:
#> ! Result 2 must be a single string, not a character vector of length 0
#> Backtrace:
#> ▆
#> 1. ├─purrr::map_chr(stuff, as.character, .null = NA_character_)
#> 2. └─purrr:::stop_bad_element_vector(...)
#> 3. └─purrr:::stop_bad_vector(...)
#> 4. └─purrr:::stop_bad_type(...)
#> 5. └─rlang::abort(...) Created on 2022-11-07 with reprex v2.0.2 Same with Apologies for posting on a closed issue. Happy to open another issue if that's preferred, though this one remains in my testing the top google hit for "purrr map NULL to NA" and related searches. |
When working with sparse nested lists (like JSON), it is common to have missing keys or NULL values, which are difficult to coerce into a desired type with purrr.
For example:
We can achieve the desired effect by mapping twice and using the
null-replace
operatorIdeally,
map_*
andflatten_*
would treatNULL
s asNA
s, possibly by default or if not then by an argument. It could throw a warning when this occurs.The options I see are:
NULL
entriesNA
s whereNULL
s were encounteredCurrently, purrr implements option 1, which will lead to difficult to debug failures when working with JSON, and a lot of duplicated code to prevent it. I believe option 2 is very dangerous (this is what
unlist
does). Hence the suggestion for option 3.The text was updated successfully, but these errors were encountered: