0

In R I have a function that creates a 10x10 matrix. If we run this function n times, what would be an easy way to calculate the average of each element in this matrix? Below is what i'm working with so far.

      for (i in 1:10) {
    Gs[,i] <- G(N, s[i], m[i] , y[i], x[, i])
  }
  return(Gs)

I want the mean for every position in the matrix of n values from the function calls. 

jogo
  • 12,469
  • 11
  • 37
  • 42
reteip
  • 23
  • 2
  • 1
    where do you put the results of your n function calls? Please edit your question. What do you mean with "average of each element in this matrix". Do you mean for every position in the matrix the mean of the n values from the function calls? If yes, construct an 3-dimensional array and use `apply()` – jogo Dec 08 '15 at 14:20
  • Yes, exactly what you stated. The mean for every position in the matrix of n values from the function calls. Thanks, I'll have a look in the apply() function – reteip Dec 08 '15 at 14:24
  • Maybe you need `Map` function here – inscaven Dec 08 '15 at 14:29
  • 2
    Welcome to StackOverflow! Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610). This will make it much easier for others to help you. – Jaap Dec 08 '15 at 15:07

1 Answers1

2

you can try:

Gs.all <- array(NA, dim=c(10, 10, n))
for (k in 1:n) Gs.all[,,k] <- f(...) # the function which returns one Gs
apply(Gs.all, 1:2, mean)
jogo
  • 12,469
  • 11
  • 37
  • 42