Search code examples
rlapplypurrrsapply

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


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.


Solution

  • 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"