lapply/purrr :: map之类的函数默认允许访问索引? [英] lapply / purrr::map like function that allows access to the index by default?
问题描述
例如
x <- list(a=11,b=12,c=13)
lapply(seq_along(x), function(y, n, i) { paste(n[[i]], y[[i]]) }, y=x, n=names(x))
是否有像s/lapply(或类似 purrr :: map()
)之类的函数,该函数允许以最简单的方式访问索引,我想这只是简单地提供所需的初始函数调用的名称,仅此而已;
Is there any function like s/lapply (or like purrr::map()
) which allows access to the index in the simplest way possible, which I guess would be to simply supply its desired name to the initial function call and nothing more;
map_with_index <- function(.x, .f, index) {
# Same as purrr::map()
# ..but whatever string is provided to 'index' parameter becomes the index
# and is accessible inside the function
}
是否已经存在某些东西,或者可以定义一个执行此操作的自定义函数?
Does something already exist, or is it possible to define a custom function that does this?
注意:有人可能会说上面的s/lapply技术可以达到要求.但是反驳的说法是,即使在MRE中,它也会增加不必要的复杂性,更不用说在复杂的现实生活中使用了,因此,进行简化很有价值.
Note: One could argue that the s/lapply technique above achieves what's required. But the counter argument is that it adds unwanted complexity even in its MRE, let alone in complicated real life settings, hence, a simplification would be valuable.
推荐答案
您需要查看 purrr :: imap
函数系列.这是一个简单的示例:
You need to look at the purrr::imap
family of functions. Here is a simple example:
set.seed(123)
s <- sample(10)
purrr::imap_chr(s, ~ paste0(.y, ": ", .x))
输出
[1] "1: 3" "2: 10" "3: 2" "4: 8" "5: 6" "6: 9" "7: 1" "8: 7" "9: 5" "10:4"
这篇关于lapply/purrr :: map之类的函数默认允许访问索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!