将循环函数应用于向量/列表时,我经常需要某种计数器/索引值。当使用基本循环函数时,可以通过向某个初始值连续加 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"
Run Code Online (Sandbox Code Playgroud)
我能够使用包中的循环函数访问此类索引值的唯一方法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"
Run Code Online (Sandbox Code Playgroud)
您正在寻找的最接近的近似值是purrr::imap,在文档中描述为
map2(x, names(x), ...)ifx有名字或map2(x, seq_along(x), ...)没有名字的简写。
以下代码有效:
lets <- letters[1:5]
purrr::imap(lets, ~print(paste(.x, "has index", .y)))
Run Code Online (Sandbox Code Playgroud)
我假设您实际上正在尝试创建一个新对象并将其存储在一个新变量中。如果您希望显示输出(如本例所示,结果是print控制台的 a),您应该使用等效的函数iwalk,以不可见的方式返回其输出。