D1X
D1X

Reputation: 5474

Using mapply() or any of its family members to call a function over vectors

I have a function that has several vector and non vector arguments:

   myfun <- function( number , vector1, vector2, number2) {
      # test function thanks to Chi Pak
      temp <- number * vector1 + max(vector2) * number2
      return(temp)
   }

I want to perform the following actions:

  1. Call this function for a vector of number, numberS.
  2. For each number above I want it to be called with one of each vector1 obtained from the list listofvectors1.
  3. vector2 and number2 are the same for each call.

In order to clarify it a bit more, this is what I would do with loops:

numberS <- c(1,2,3)
listofvectors1 <- list(c(1,2,3), c(5,6,7,8), c(0,1) ) # Obviously has the same length as numberS
vector2 <- c(0.5,3,1)
number2 <- 3.14

for (i in 1:length(numberS)){
   myfun(numberS[i], listofvectors1[[i]], vector2, number2)
}

I want to do this using a function like apply(), I have been trying using mapply() but I can't make it work, as it either nests all the vectors or simply doesn't nest anything.

Upvotes: 0

Views: 158

Answers (2)

Hong Ooi
Hong Ooi

Reputation: 57696

Use the MoreArgs argument to specify those arguments you don't want to vectorise over.

mapply(myfun, NumberS, listofvectors1, MoreArgs=list(vector2, number2))

Upvotes: 3

CPak
CPak

Reputation: 13581

Reproducible example

A test myfun function

myfun <- function( number , vector1, vector2, number2) {
      temp <- number * vector1 + max(vector2) * number2
      return(temp)
   }

Your values

numberS <- c(1,2,3)
listofvectors1 <- list(c(1,2,3), c(5,6,7,8), c(0,1) ) # Obviously has the same length as numberS
vector2 <- c(0.5,3,1)
number2 <- 3.14

You can use lapply like this

lapply(1:length(numberS), function(x) myfun(numberS[x], listofvectors1[[x]], vector2, number2))

# [[1]]
# [1] 10.42 11.42 12.42
# etc

Or purrr::map2 like this

library(purrr)
map2(numberS, listofvectors1, ~myfun(.x, .y, vector2, number2))

# [[1]]
# [1] 10.42 11.42 12.42
# etc

Upvotes: 1

Related Questions