R apply function with multiple parameters

Just pass var2 as an extra argument to one of the apply functions.

mylist <- list(a=1,b=2,c=3)
myfxn <- function(var1,var2){
  var1*var2
}
var2 <- 2

sapply(mylist,myfxn,var2=var2)

This passes the same var2 to every call of myfxn. If instead you want each call of myfxn to get the 1st/2nd/3rd/etc. element of both mylist and var2, then you're in mapply's domain.


To further generalize @Alexander's example, outer is relevant in cases where a function must compute itself on each pair of vector values:

vars1 <- c(1,2,3)
vars2 <- c(10,20,30)
mult_one <- function(var1, var2)
{
   var1*var2
}
outer(vars1, vars2, mult_one)

gives:

> outer(vars1, vars2, mult_one)
     [,1] [,2] [,3]
[1,]   10   20   30
[2,]   20   40   60
[3,]   30   60   90

If your function have two vector variables and must compute itself on each value of them (as mentioned by @Ari B. Friedman) you can use mapply as follows:

vars1 <- c(1, 2, 3)
vars2 <- c(10, 20, 30)
mult_one <- function(var1, var2)
{
   var1*var2
}
mapply(mult_one, vars1, vars2)

which gives you:

> mapply(mult_one, vars1, vars2)
[1] 10 40 90

Tags:

R