Bratt Swan Bratt Swan - 2 months ago 7
R Question

How to repeat same codes in 10 times and get those results in R?

Here is my code:

f.x <- function(x) {
60*x^3*(1-x)^2
}

x <- seq(0, 1, length=100)
n.samps <- 1000
n <- 0 # counter for accepted
i <- 0 # iterations
samps <- numeric(n.samps)

while (n < n.samps) {
y <- runif(1)
i <- i + 1
u <- runif(1)
if (u < f.x(y) / 2.0736) {
n <- n + 1
samps[n] <- y
}
}


I want to repeat the code above for 10 times, each time an "i" will be produced. I want to take the average of these ten "i". Instead of run the code each time, is there any way I can run one time but get 10 trials?

Answer

You can try placing your entire script into a function, and then just call it 10 times from a loop:

getValue <- function() {
    x <- seq(0, 1, length=100)
    n.samps <- 1000
    n <- 0  # counter for accepted
    i <- 0  # iterations
    samps <- numeric(n.samps)

    while (n < n.samps) {
        y <- runif(1)
        i <- i + 1
        u <- runif(1)
        if (u < f.x(y) / 2.0736) {
            n <- n + 1
            samps[n] <- y
        }
    }

    return(i)
}

Usage:

result <- replicate(10, getValue())