[r] passing several arguments to FUN of lapply (and others *apply)

I have a question regarding passing multiple arguments to a function, when using lapply in R.

When I use lapply with the syntax of lapply(input, myfun); - this is easily understandable, and I can define myfun like that:

myfun <- function(x) {
 # doing something here with x
}

lapply(input, myfun);

and elements of input are passed as x argument to myfun.

But what if I need to pass some more arguments to myfunc? For example, it is defined like that:

myfun <- function(x, arg1) {
 # doing something here with x and arg1
}

How can I use this function with passing both input elements (as x argument) and some other argument?

This question is related to r lapply

The answer is


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


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


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).