Default value to replace NULL #110
Comments
Maybe issues %>% map(c("milestone", "title")) %>% map_chr(empty = "") |
Or make it explicit pluck <- function(y, default = NULL) {
function(x) {
x[[y]] %||% default
}
}
issues %>% map_chr(pluck(c("milestone", "title"), "")) Or pluck <- function(..., default = NULL) {
y <- c(...)
function(x) {
x[[y]] %||% default
}
}
issues %>% map_chr(pluck("milestone", "title", default = "")) But second form makes you think that |
I think this is what this issue is about? Hope it's in the right place. I'm trying to use a character vector as extractor function in library(purrr)
x <- list(one = list(always = "a", sometimes = "b"),
two = list(always = "b", sometimes = NULL))
x %>% map_chr("always")
#> one two
#> "a" "b"
x %>% map_chr("sometimes")
#> Error in map_chr(., "sometimes"): Result 2 is not a length 1 character This seems to get the job done for the time being: x %>%
map("sometimes") %>%
map_if(is.null, ~ NA_character_) %>%
flatten_chr()
#> [1] "b" NA |
This is what it would look like with library(purrr)
x <- list(
one = list(always = "a", sometimes = "b"),
two = list(always = "b", sometimes = NULL)
)
x %>% map_chr("always")
x %>% map_chr(pluck("sometimes", NA_character_)) But it should probably be an adverb: hopefully <- function(.f, default = NULL) {
.f <- as_function(.f)
function(x) {
.f(x) %||% default
}
}
x <- list(
one = list(always = "a", sometimes = "b"),
two = list(always = "b", sometimes = NULL)
)
x %>% map_chr(hopefully("sometimes", NA_character_)) (But hopefully isn't the best name!) |
could be
|
I like |
This also feels a lot like data import and declaring how missing values present themselves, e.g. An adverb feels a bit odd because it feels more like data is getting modified, than a function. Even though I do understand that when I say ' |
@jennybc hmmm, that's true and now that I think about it, there's no reason that |
And maybe |
I think How do we signal we want to ignore NULLs and possibly get an output smaller than the input? |
Or |
@lionel- I was thinking and realised empty isn't quite right because you're actually indexing into elements that don't exist (not just that they're empty). And the same constraints still apply to map - the output has to be the same length as the input. |
The problem with |
How about |
I think |
But |
A drop-in value for values that didn't exist? Is that a default? Fallback?
|
oooh I was confused. I thought it was about giving a default to actual Since one peculiarity of the R language is that indexing absent values also yields mtcars$absent$absent
#> NULL And then the argument |
@tjmahr I may like It would also work for actual |
@lionel- the inconsistency is that |
The text was updated successfully, but these errors were encountered: