Length recycling with map_*
olivroy opened this issue · 1 comments
olivroy commented
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 commented
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