-5

Consider a function that takes in two input arguments and returns a dataframe:

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

myFun(1, 1)

A double loop can be constructed over each of the arguments of this function:

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)

How to replace this double loop with an apply construct?

Aditya
  • 1,554
  • 1
  • 13
  • 23

1 Answers1

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

dplyr::bind_rows(resList)
Aditya
  • 1,554
  • 1
  • 13
  • 23