Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Utilizing a vectors index number when using map

Tags:

r

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

like image 907
DJC Avatar asked Sep 12 '25 19:09

DJC


2 Answers

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
like image 54
akrun Avatar answered Sep 15 '25 10:09

akrun


Or:

library(tidyverse)

c(2, 3) %>% 
  map2_dbl(1:length(.), ~.x + .y)

#> [1] 3 5
like image 45
PaulS Avatar answered Sep 15 '25 08:09

PaulS