How to repeat same codes in 10 times and get those results in R? -
here code:
f.x <- function(x) { 60*x^3*(1-x)^2 } x <- seq(0, 1, length=100) n.samps <- 1000 n <- 0 # counter accepted <- 0 # iterations samps <- numeric(n.samps) while (n < n.samps) { y <- runif(1) <- + 1 u <- runif(1) if (u < f.x(y) / 2.0736) { n <- n + 1 samps[n] <- y } }
i want repeat code above 10 times, each time "i" produced. want take average of these ten "i". instead of run code each time, there way can run 1 time 10 trials?
you can try placing entire script function, , call 10 times loop:
getvalue <- function() { x <- seq(0, 1, length=100) n.samps <- 1000 n <- 0 # counter accepted <- 0 # iterations samps <- numeric(n.samps) while (n < n.samps) { y <- runif(1) <- + 1 u <- runif(1) if (u < f.x(y) / 2.0736) { n <- n + 1 samps[n] <- y } } return(i) }
usage:
result <- replicate(10, getvalue())
Comments
Post a Comment