【发布时间】:2019-06-08 08:11:15
【问题描述】:
在将循环函数应用于向量/列表时,我经常需要某种计数器/索引值。使用基本循环函数时,可以通过将某个初始值连续加 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"
【问题讨论】: