R apply function with multiple parameters

R

R Problem Overview


I have a function f(var1, var2) in R. Suppose we set var2 = 1 and now I want to apply the function f() to the list L. Basically I want to get a new list L* with the outputs

[f(L[1],1),f(L[2],1),...,f(L[n],1)]

How do I do this with either apply, mapply or lapply?

R Solutions


Solution 1 - R

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.

Solution 2 - R

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

Solution 3 - R

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichaelView Question on Stackoverflow
Solution 1 - RAri B. FriedmanView Answer on Stackoverflow
Solution 2 - RAlexanderView Answer on Stackoverflow
Solution 3 - RMartin SmithView Answer on Stackoverflow