tidyverse / purrr

A functional programming toolkit for R
https://purrr.tidyverse.org/
Other
1.28k stars 272 forks source link

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

Closed Dannyzhd closed 4 months ago

Dannyzhd commented 1 year ago

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_rawinstead 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 commented 4 months ago

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