Search code examples
rloopssapply

Using sapply instead of loop in R


I have a function that requires 4 parameters:

myFun <- function(a,b,c,d){}

I have a matrix where each row contains the parameters:

myMatrix = matrix(c(a1,a2,b1,b2,c1,c2,d1,d2), nrow=2, ncol=4)

Currently I have a loop which feeds the parameters to myFun:

m <- myMatrix
i <- 1
someVector <- c()
while (i<(length(m[,1])+1)){
    someVector[i] <- 
    myFun(m[i,1],m[i,2],m[i,3],m[i,4])
    i = i+1
}
print(someVector)

What I would like to know is there a better way to get this same result using sapply instead of a loop.


Solution

  • You can use mapply() here which allows you to give it vectors as arguments, you should turn your matrix into a dataframe.

    df <- as.data.frame(myMatrix))
    
    results <- mapply(myFun, df$a, df$b, df$c, df$d)