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

Unexpected behavior of map() and pluck() #1108

Closed
Dannyzhd opened this issue Nov 10, 2023 · 1 comment
Closed

Unexpected behavior of map() and pluck() #1108

Dannyzhd opened this issue Nov 10, 2023 · 1 comment

Comments

@Dannyzhd
Copy link

Dannyzhd commented Nov 10, 2023

Dear developers.

I was doing exercise of Advanced R 9.2.7. Question2.

map(1:3, ~ runif(2)) is a useful pattern for generating random numbers, but map(1:3, runif(2)) is not. Why not? Can you explain why it returns the result that it does?

for the map(1:3, runif(2)) my understanding is that since runif(2) is not a function-type variable, it is instead turned by as_mapper() as a indexing function driven by purrr::pluck() with the index series being provided by runif(2)

without lost of generality let's say runif(2) returns us
Screen Shot 2023-11-10 at 3 26 47 PM

Thus map(1:3, runif(2)) is essentially equivalent to

map(1:3, function(x){pluck(x, 0.05562636, 0.70005192)})

which, in my understanding, should give an integer(0) as r basically truncate the index by using only the integer part, which in this case is 0.

However it seems, instead the function is automatically rounding the indices into 1 while performing the index.
Resulting in for each iteration we index it by 1 twice, resulting in itself.

Screen Shot 2023-11-10 at 3 46 27 PM Screen Shot 2023-11-10 at 3 46 59 PM

I guess maybe this is due to the as_mapper actually using pluck_raw instead of pluck as the as_mapper(runif(2)) indicates
Screen Shot 2023-11-10 at 3 35 39 PM

But for this pluck_raw I could not find the document so it is hard to predict its behavior.

Could you guide my to the document for this behaviour of rounding performed by purrr::map when .f is treated as indexing function by as_mapper()?

Thanks in advance for reviewing my qeustion.

@hadley
Copy link
Member

hadley commented Jul 15, 2024

I think this is just inherited from base R which truncates doubles when indexing:

c(1, 2, 3)[1.5]
#> [1] 1

Created on 2024-07-15 with reprex v2.1.0

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