如何重复10次相同的代码,并在R?

时间:2016-09-13 04:23:38

标签: r

这是我的代码:

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
    }
}

我想重复上面的代码10次,每次都会产生“i”。我想取这十个“我”的平均值。而不是每次运行代码,有没有什么方法可以运行一次,但获得10次试验?

1 个答案:

答案 0 :(得分:1)

您可以尝试将整个脚本放入一个函数中,然后从循环中调用它10次:

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)
}

<强>用法:

result <- replicate(10, getValue())