176

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?

1

3 Answers 3

234

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.

4
  • 5
    but note that myfxn may be vectorised, in which case one should use myfxn(unlist(mylist), var2=var2)
    – baptiste
    Commented Jul 26, 2011 at 21:08
  • The original example was unclear but seemed to be to be non-vectorized. Point well taken, however. Commented Jul 26, 2011 at 21:14
  • Is the a way to make this work as a function "on the fly?" Something like this: sapply(mylist, function(var1, var2) { var1*var2 }, var=thisvar2) But I get an error that argument 2 matches multiple formal arguments
    – emudrak
    Commented Jan 26, 2017 at 18:43
  • 1
    @emudrak I think the problem there is jus that you're naming the argument you pass var instead of var2. R can't divine what you mean. Commented Jan 30, 2017 at 14:32
86

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
3
  • 6
    One upvote for generalizing, even with a simple and clear example.
    – JASC
    Commented Dec 27, 2018 at 17:51
  • 3
    mapply will also recycle if vars1 has a single element. For example when vars1 <- 3, mapply(mult_one, vars1, vars2) returns 30 60 90. This is useful when you want to use lapply over the second argument of a function. Commented Jun 10, 2019 at 9:12
  • 1
    Does mapply work with more than 2 arguments in the fucntion ?
    – Julien
    Commented Jul 2, 2022 at 17:48
15

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.