I often need some sort of counter / index value when applying loop-functions to vectors / list. When using basic loop functions, this index can be created by successively adding 1 to some initial value. Consider the following example:
lets <- letters[1:5]
n = 0
for (le in lets){
n = n+1
print(paste(le,"has index",n))
}
#> [1] "a has index 1"
#> [1] "b has index 2"
#> [1] "c has index 3"
#> [1] "d has index 4"
#> [1] "e has index 5"
The only way I've been able to access such an index value with the loop-functions from the purrr
package is using map2
. Is there a more elegant way to do this using only purrr::map()
?
library(purrr)
map2(lets,1:length(lets),~paste(.x,"has index",.y))
#> [[1]]
#> [1] "a has index 1"
#>
#> [[2]]
#> [1] "b has index 2"
#>
#> [[3]]
#> [1] "c has index 3"
#>
#> [[4]]
#> [1] "d has index 4"
#>
#> [[5]]
#> [1] "e has index 5"