简体   繁体   中英

Use lapply with keyword arguments

So if I am not missing something big, the way lapply/sapply/etc. works is by using the iterable element in the list as first argument, therefore forcing you to use it as positional argument of the function ( FUN ).

So a normal use case would be

foo <- function(a = NULL, b = NULL, c = NULL) {
  print(glue::glue("a: {a}"))
  print(glue::glue("b: {b}"))
  print(glue::glue("c: {c}"))
}

lapply(letters[1:3], foo)
#> a: a
#> 
#> 
#> a: b
#> 
#> 
#> a: c
#> [[1]]
#> 
#> 
#> [[2]]
#> 
#> 
#> [[3]]

However, if I want to iterate through the list as b instead, I am forced to set a value to a. Like this.

lapply(letters[1:3], foo, a = NULL)
#> 
#> b: a
#> 
#> 
#> b: b
#> 
#> 
#> b: c
#> [[1]]
#> 
#> 
#> [[2]]
#> 
#> 
#> [[3]]
lapply(letters[1:3], foo, a = NULL,b = NULL )
#> 
#> 
#> c: a
#> 
#> 
#> c: b
#> 
#> 
#> c: c
#> [[1]]
#> c: a
#> 
#> [[2]]
#> c: b
#> 
#> [[3]]
#> c: c

I know I can set it to the default value but I would like to know if there is a way to use the iterated elements as keyword argument instead of positional argument.

It would also be handy for the purrr::map family but as far as I looked such option is not available either.

Created on 2019-12-24 by the reprex package (v0.3.0)

Simply define a new anonymous function to associate the argument with the name, eg

lapply(letters[1:3], function(x) foo(b = x))

If you're using purrr , there's a bit less typing, but conceptually you're doing the same thing:

purrr::map(letters[1:3], ~ foo(b = .))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM