[R] Simulation based on runif to get mean

Daniel Nordlund djnordlund at gmail.com
Tue Jan 30 09:58:40 CET 2018

On 1/29/2018 9:03 PM, smart hendsome via R-help wrote:
> Hello everyone,
> I have a question regarding simulating based on runif.  Let say I have generated matrix A and B based on runif. Then I find mean for each matrix A and matrix B.  I want this process to be done let say 10 times. Anyone can help me.  Actually I want make the function that I can play around with the number of simulation process that I want. Thanks.
> Eg:
> a <- matrix(runif(5,1, 10))
> b <- matrix(runif(5,10, 20))
> c <- cbind(a,b); c
> mn <- apply(c,2,mean); mn
> Regards,
> Zuhri
> 	[[alternative HTML version deleted]]
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

Here is a straight forward implementation of your code in a function 
with a parameter for the number simulations you want to run.

sim <- function(n){
   mn <- matrix(0,n, 2)
   for(i in 1:n) {
     a <- runif(5,1, 10)
     b <- runif(5,10, 20)
     c <- cbind(a,b)
     mn[i,] <- apply(c, 2, mean)
# run 10 iterations

In your case, there doesn't seem to be a need to create a and b as 
matrices; vectors work just as well.  Also, several of the statements 
could be combined into one.  Whether this meets your needs depends on 
what your real world task actually is.

Hope this is helpful,


Daniel Nordlund
Port Townsend, WA  USA

More information about the R-help mailing list