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

Length recycling with map_* #1081

Closed
olivroy opened this issue May 25, 2023 · 1 comment
Closed

Length recycling with map_* #1081

olivroy opened this issue May 25, 2023 · 1 comment

Comments

@olivroy
Copy link

olivroy commented May 25, 2023

I was wondering if there was a workaround for length recycling in purrr.

for

li <- list(list(x = 1, y = 2), list(x = 2, w = 3), list(w = 23, y = 4))
map(li, "w")
[[1]]
NULL
[[2]]
3
[[3]]
23
map_int(li, "w")
Error in `map_int()`:In index: 1.
Caused by error:
! Result must be length 1, not 0.
# The workaround I used is
map_int(li, \(x) x$w %||% NA)
[[1]]
NULL
[[2]]
3
[[3]]
23
# but it is not as elegant as the first solution

Edit: there is also dplyr::coalesce(list, list(NA)), but again, not as elegent.

@hadley
Copy link
Member

hadley commented Jul 26, 2023

You can use the .default argument:

library(purrr)

li <- list(list(x = 1, y = 2), list(x = 2, w = 3), list(w = 23, y = 4))
map_int(li, "w", .default = NA)
#> [1] NA  3 23

Created on 2023-07-26 with reprex v2.0.2

@hadley hadley closed this as completed Jul 26, 2023
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

2 participants