[英]Using sapply instead of loop in R
I have a function that requires 4 parameters:我有一个需要 4 个参数的函数:
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:目前我有一个循环将参数提供给 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.我想知道是否有更好的方法使用 sapply 而不是循环来获得相同的结果。
You can use mapply()
here which allows you to give it vectors as arguments, you should turn your matrix into a dataframe.您可以在这里使用mapply()
,它允许您将向量作为参数,您应该将矩阵转换为数据框。
df <- as.data.frame(myMatrix))
results <- mapply(myFun, df$a, df$b, df$c, df$d)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.