4

I am new to R, hence I am new to the apply functions. I haven't found the answer to this question anywhere, even though I have a (not so elegant) way of solving it.

Consider this dummy code:

my.fun <- function(vector1, vector2, vector3 = NULL) {
    # do stuff with the vectors
}

list1 <- mapply(FUN = my.fun, arg1, arg2, list(arg3), SIMPLIFY = FALSE)

Suppose arg1 and arg2 are lists (of the same length) that I want to iterate inside the mapply function, but arg3 is simply a vector that I want to use in my.fun() without being iterated. My question is: how do I put arg3 available in my.fun() in all of the mapply function iterations? To clarify, the vector3 in my.fun() should be the equal to arg3, outside my.fun().

One way of doing this is:

list1 <- mapply(FUN = my.fun, arg1, arg2, rep(list(arg3), length(arg1)), SIMPLIFY = FALSE)

But it looks like there should be a more elegant way.

Is there a way of specifying which arguments are iterated and which aren't? Or doing the same thing (with an apply-family function) without having to create a lot of copies of the same thing?

Thank you for any advice.

jose
  • 220
  • 1
  • 12

2 Answers2

4

mapply() has a MoreArgs= argument intended for just this purpose.

For example:

par(mfcol=c(2,2), ann=FALSE, mar=c(1,1,1,1))
mapply(plot, x=1:4, y=4:1, col=1:4,
       MoreArgs=list(xlim=c(1,4), ylim=c(1,4), pch=16, cex=3))

enter image description here

Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
0

One way to do this is use the Map function along with an anonymous function. Here is an example

myFunction <- function(arg1, arg2, arg3) {
  arg1 + arg2 + arg3
}

arg1 <- 1:5
arg2 <- 5:1
arg3 <- 1

Map(function(arg1, arg2) myFunction(arg1, arg2, arg3=arg3), arg1, arg2)
lmo
  • 37,904
  • 9
  • 56
  • 69