Reputation: 6652
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.
b
and use 1:5
for c
?1:5
as an xyz
argument in the ...
?Upvotes: 6
Views: 1026
Reputation: 2253
You can use mapply
to specify static and dynamic arguments explicitly:
mapply(cbind, a = "a constant", b = 1:5, SIMPLIFY = FALSE)
Upvotes: 0
Reputation: 132706
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)
Upvotes: 7
Reputation: 521289
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)
})
Upvotes: 2