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

map_* expects a vector of length 1 #518

Closed
rmflight opened this issue Jun 20, 2018 · 6 comments
Closed

map_* expects a vector of length 1 #518

rmflight opened this issue Jun 20, 2018 · 6 comments

Comments

@rmflight
Copy link
Contributor

This isn't really documented in the map_* that these functions expect a length 1 vector.

It is disconcerting, b/c the map_df* functions don't care how big the resulting objects are, they just get merged together.

Small pull request to update the documentation.

@rmflight
Copy link
Contributor Author

For example, I really expect this to work:

l1 <- list(list(a = 1L),
           list(a = c(1L, 2L, 3L)))

purrr::map_int(l1, "a")
#> Error: Result 2 is not a length 1 atomic vector

purrr::map_chr(l1, function(x){class(x$a)})
#> [1] "integer" "integer"

@jennybc
Copy link
Member

jennybc commented Jun 20, 2018

In terms of getting what you want, map() followed by a type-specific flatten_*() does it:

library(purrr)

l1 <- list(list(a = 1L),
           list(a = c(1L, 2L, 3L)))

map(l1, "a") %>% flatten_int()
#> [1] 1 1 2 3

@rmflight
Copy link
Contributor Author

rmflight commented Jun 20, 2018 via email

@egnha
Copy link
Contributor

egnha commented Jun 20, 2018

@rmflight I hope I am not adding noise to the discussion, but what about the first line of the description of the map functions?:

The map functions transform their input by applying a function to each element and returning a vector the same length as the input.

Does this not imply that the function to be mapped by map_*() must return a scalar? (But you are right that it is not explicitly stipulated. If that is what's tripping up users, then I see your point.)

@jennybc
Copy link
Member

jennybc commented Jun 20, 2018

I proposed some wording in the PR: #517 (comment)

@cderv
Copy link
Contributor

cderv commented Jun 21, 2018

Not about the wording but for reference about the use case needing flatten after map, there is an open PR #502 adding map_flat_* functions.

# devtools::install_github("tidyverse/purrr#502)
library(purrr)
l1 <- list(list(a = 1L),
           list(a = c(1L, 2L, 3L)))

map_flat_int(l1, "a")
#> [1] 1 1 2 3

Created on 2018-06-21 by the reprex package (v0.2.0).

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

4 participants