Specify which argument is supplied by X in lapply
Asked Answered
S

3

6

I've got a function, e.g. fun(a, b = 1, c = 3, ...), that takes a number of arguments, some of which have default values. I would like to call this function using lapply(X, FUN, ...), but specify explicitly which argument I would like X to supply. In the example above, the X vector could be supplied for a or b or c, or xyz in the ....

Normally I might call lapply(1:5, fun, a = 4) and I imagine it would use 1:5 as the b argument.

  • Is there a way to make that more explicit?
  • What if I want to use the default argument for b and use 1:5 for c?
  • What if I want to use 1:5 as an xyz argument in the ...?
Sigrid answered 13/5, 2016 at 6:48 Comment(4)
Please provide a reproducible example and expected outputDissimilar
The general syntax should work lapply(1:5,function(x,a=4,..,) { } )Erick
Why would you want to pass other variables to the function? lapply itself will only give you a single entry from the list on which it is operating.Ribband
It assigns to the first otherwise unassigned parameter. If you want to be super-clear–or the parameter you want to assign to is not the next one–just wrap the call in an anonymous function.Lakshmi
Z
7

Normally I might call lapply(1:5, fun, a = 4) and I imagine it would use 1:5 as the b argument.

Yes, your imagination is correct. lapply uses positional matching to pass its X parameter to the function. Normal rules of argument matching apply, which means exact matching of named parameters takes precedence.

An alternative would of course be to wrap fun in an anonymous function:

lapply(1:5, function(b, a, ...) fun(a = a, b = b, ...), a = 4)
Zabrina answered 13/5, 2016 at 6:59 Comment(0)
R
2

One way to handle you use case would be to simply call your own function inside the custom function which lapply exposes to you:

lst <- list(v1=c(1:3), v2="Hello", v3=5)

result <- lapply(lst, function(x) {
                         y <- FUN(x, a, b, c, ...)   # Here FUN() is your own function
                         return(y)
                      })
Ribband answered 13/5, 2016 at 6:58 Comment(0)
T
0

You can use mapply to specify static and dynamic arguments explicitly:

mapply(cbind, a = "a constant", b = 1:5, SIMPLIFY = FALSE)
Toplevel answered 4/6, 2023 at 14:45 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.