Skip to content
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

yet another form of nothing for type-specific map_*() to handle #181

Closed
jennybc opened this issue Mar 3, 2016 · 4 comments
Closed

yet another form of nothing for type-specific map_*() to handle #181

jennybc opened this issue Mar 3, 2016 · 4 comments

Comments

@jennybc
Copy link
Member

jennybc commented Mar 3, 2016

Continuing our exploration of nothingness (#110).

It seems type specific map functions should be willing to cope with length zero elements and treat them as null/absent.

library(purrr)
x <- list(one = list(always = "a", sometimes = "b"),
          two = list(always = "b", sometimes = character()))
x %>% map_chr("always")
#> one two 
#> "a" "b"
x %>% map_chr("sometimes")
#> Error: Result 2 is not a length 1 atomic vector

This seems to get the job done for the time being:

x %>%
  map("sometimes") %>%
  map_if(is_empty, ~ NA_character_) %>% 
  flatten_chr()
#> [1] "b" NA

FYI: inspired by an actual list that came from JSON, that came from the Twitter API.

@hadley
Copy link
Member

hadley commented Mar 25, 2016

This is a duplicate of #173

@hadley hadley closed this as completed Mar 25, 2016
@jennybc
Copy link
Member Author

jennybc commented Mar 25, 2016

I don't entirely understand why this is a duplicate. @hadley

library(purrr)
x <- list("a" = list("b" = character()))
x[[c("a", "b")]]
#> character(0)
x %>% map("b")
#> $a
#> character(0)
x %>% map_chr("b")
#> Error: Result 1 is not a length 1 atomic vector

@hadley
Copy link
Member

hadley commented Mar 25, 2016

Because map_chr calls [[. It makes sense to me anyway, so I'll remember

@almartin82
Copy link

Closed issue, but leaving for anyone who is cleaning up JSON and stumbles into this same problem - I resolved this by writing a wrapper around @jennybc's great workaround above:

 map_null_chr <- function(.x, .f) {
   map(.x, .f) %>%
     map_if(is_empty, ~ NA_character_) %>%
     flatten_chr()
 }

And replaced my offending map_chr call.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants