I have a function which utilizes purrr::map
. I would like to access the index number of the vector element being used in the map function.
In the example below, I would like to add the index number to each value:
library(tidyverse)
c(2, 3) %>%
map_dbl(~.x + [index])
So, for example, for the first element, 2
, the map function would evaluate and return:
2 + 1 = 3, where 1 = its index in the source vector
Whereas for the second element, 3
, the map function would evaluate and return:
3 + 2 = 5, where 2 = its index in the source vector
Instead of map
, use imap
, which returns the index with .y
(if not named). It is mentioned in the documentation of ?imap
imap_xxx(x, ...), an indexed map, is short hand for map2(x, names(x), ...) if x has names, or map2(x, seq_along(x), ...) if it does not.
c(2, 3) %>%
imap_dbl(~ .x + .y )
-output
[1] 3 5
Or:
library(tidyverse)
c(2, 3) %>%
map2_dbl(1:length(.), ~.x + .y)
#> [1] 3 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With