-5

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

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 构造替换这个双循环?

4

1 回答 1

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

dplyr::bind_rows(resList)
于 2015-08-13T07:36:18.277 回答