Search code examples
loopsstatisticssampleuniform-distribution

Creating a function that repeatedly draws from a uniform random variable 10000x and calculating the sample mean and variance for each draw (R)


Question at hand

Hello, I am relatively new to R. I have taken about 2 months of courses, but I have not really actually applied my skills regularly. Fortunately, I am taking a stats course that is pushing me to do just (I am so excited about it).

Anyways, I would like to know the different ways one would approach this. Here is what I have so far(not much):

z <- runif(n = 100, min= 0, max = 1) mean(z)

I know it is not much, but I do suspect that there are several ways to do this. The way I think it can be done efficiently is by running a for-loop. For example

times <- 10000

for (i in 1:times){runif(n=100, min = 0, max =1)}

I KNOW this may not be even close to correct, which why I ask here. Any guidance is appreciated. Thank you.

It is important that I am mainly referring to part b).


Solution

  • I don't know if I understood well what you are trying to do, but using a loop seems good to me.

    If you want to get the mean & variance of each of your 10000 samples, then this should work :

    mean_and_variance <- function(times)
    {
        res <- matrix(rep(0,times*2), nrow = times, ncol = 2)
        for (i in 1:times)
        {
            z <- runif(n=100, min = 0, max =1)
            res[i,] <- c(mean(z),var(z))
        }
        colnames(res) <- c("mean", "variance")
        return(res)
    }
    

    res is a matrix of dimension times*2. each row corresponds to the couple (mean,variance) for the sample generated in the loop.

    if I didn't understand well your question feel free to tell me.

    best regards