lapply / purrr::map like function that allows access to the index by default?

帅比萌擦擦* 提交于 2021-02-20 04:29:08

问题


There's a workaround to allow access the index inside a s/lapply

e.g.

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))

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?

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.


回答1:


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))

Output

[1] "1: 3"  "2: 10" "3: 2"  "4: 8"  "5: 6"  "6: 9"  "7: 1"  "8: 7"  "9: 5"  "10:4"


来源:https://stackoverflow.com/questions/62795600/lapply-purrrmap-like-function-that-allows-access-to-the-index-by-default

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!