In the purrr
package, there are the functions imap()
and iwalk()
. They take a list and a function with two arguments and apply the function to every element of the list and its index/name. The difference is, that iwalk
silently returns NULL
and is executed only for side effects (helpful if you map over cat()
) and imap()
works similar to lapply()
only it uses the functions second argument for the list's names.
library(purrr)
lst <- list(a1 = 5:12, b4 = c(34,12,5), c3 = 23:45)
imap(lst,\(x,y) cat("The name of the current list element is", y, "\n"))
#> The name of the current list element is a1
#> The name of the current list element is b4
#> The name of the current list element is c3
#> $a1
#> NULL
#>
#> $b4
#> NULL
#>
#> $c3
#> NULL
iwalk(lst,\(x,y) cat("The name of the current list element is", y, "\n"))
#> The name of the current list element is a1
#> The name of the current list element is b4
#> The name of the current list element is c3
Created on 2022-01-18 by the reprex package (v2.0.1)