Purrr Map *功能系列中的计数器

时间:2019-01-14 10:36:29

标签: r for-loop purrr

在将循环函数应用于向量/列表时,我经常需要某种计数器/索引值。使用基本循环功能时,可以通过将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"

2 个答案:

答案 0 :(得分:1)

尝试imap

lets <- letters[1:5]
purrr::imap(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将使用.x元素的名称作为.y参数(如果已命名)。如果您不想使用imap(unname(...), ...)-多亏@Moody_Mudskipper。

答案 1 :(得分:1)

与您要查找的内容最接近的是purrr::imap,在文档中将其描述为

  

如果map2(x, names(x), ...)有名字,则为x的简写,否则为map2(x, seq_along(x), ...)

以下代码有效:

lets <- letters[1:5]

purrr::imap(lets, ~print(paste(.x, "has index", .y)))

我假设您实际上是在尝试创建一个新对象并将其存储在新变量中。如果要显示输出(如本例所示,结果是控制台上的print),则应使用等效的函数iwalk,该函数会无形地返回其输出。