passing several arguments to FUN of lapply (and others *apply)
You can do it in the following way:
myfxn <- function(var1,var2,var3){
var1*var2*var3
}
lapply(1:3,myfxn,var2=2,var3=100)
and you will get the answer:
[[1]] [1] 200
[[2]] [1] 400
[[3]] [1] 600
myfun <- function(x, arg1) {
# doing something here with x and arg1
}
x
is a vector or a list and myfun
in lapply(x, myfun)
is called for each element of x
separately.
Option 1
If you'd like to use whole arg1
in each myfun
call (myfun(x[1], arg1)
, myfun(x[2], arg1)
etc.), use lapply(x, myfun, arg1)
(as stated above).
Option 2
If you'd however like to call myfun
to each element of arg1
separately alongside elements of x
(myfun(x[1], arg1[1])
, myfun(x[2], arg1[2])
etc.), it's not possible to use lapply
. Instead, use mapply(myfun, x, arg1)
(as stated above) or apply
:
apply(cbind(x,arg1), 1, myfun)
or
apply(rbind(x,arg1), 2, myfun).
As suggested by Alan, function 'mapply' applies a function to multiple Multiple Lists or Vector Arguments:
mapply(myfun, arg1, arg2)
See man page: https://stat.ethz.ch/R-manual/R-devel/library/base/html/mapply.html
If you look up the help page, one of the arguments to lapply
is the mysterious ...
. When we look at the Arguments section of the help page, we find the following line:
...: optional arguments to ‘FUN’.
So all you have to do is include your other argument in the lapply
call as an argument, like so:
lapply(input, myfun, arg1=6)
and lapply
, recognizing that arg1
is not an argument it knows what to do with, will automatically pass it on to myfun
. All the other apply
functions can do the same thing.
An addendum: You can use ...
when you're writing your own functions, too. For example, say you write a function that calls plot
at some point, and you want to be able to change the plot parameters from your function call. You could include each parameter as an argument in your function, but that's annoying. Instead you can use ...
(as an argument to both your function and the call to plot within it), and have any argument that your function doesn't recognize be automatically passed on to plot
.