替换double / nested for循环over函数,返回带有apply in R的数据帧

时间:2015-08-13 07:36:18

标签: r loops for-loop apply mapply

考虑一个接受两个输入参数并返回数据帧的函数:

myFun <- function(a, b){
   data.frame(aSQ = a^2, bSQ = b^2, SQPROD = a^2*b^2)
}

myFun(1, 1)

可以在此函数的每个参数上构造一个双循环:

results <- as.data.frame(matrix(0, nrow = 9, ncol = 3, 
                         dimnames = list(c(), c('aSQ', 'bSQ', 'SQPROD'))))
for (a in 1:3)
   for (b in 1:3)
      results[(a-1)*3+b, ] <- myFun(a, b)

如何用apply构造替换这个双循环?

1 个答案:

答案 0 :(得分:1)

resList <- mapply(
   myFun,
   a = rep(1:3, times = 3), 
   b = rep(1:3, each  = 3), 
   SIMPLIFY = FALSE
)

dplyr::bind_rows(resList)