简体   繁体   中英

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM