在对向量/列表应用循环函数时,我经常需要某种计数器/索引值。使用基本的循环函数时,可以通过将1逐步添加到某个初始值来创建此索引。考虑以下示例:
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"
我使用purrr
包中的循环函数通过map2
才能访问此类索引值。是否有更优雅的方法只使用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"
imap
将使用元素的名称作为.y
。在这种情况下,请先使用unname
函数取消元素的命名! - moodymudskipper