抛硬币.成功,你赢了100,否则你输了50.你会继续玩,直到你的口袋里有钱a.如何a存储任何迭代的值?
a <- 100
while (a > 0) {
if (rbinom(1, 1, 0.5) == 1) {
a <- a + 100
} else {
a <- a - 50
}
}
Run Code Online (Sandbox Code Playgroud)
作为最终结果,当while循环结束时,我希望能够查看a每次迭代的值,而不仅仅是最终结果.我查阅了关于计算迭代次数的帖子,但我无法将其应用于此案例.
将初始值存储a在第二个向量中,并a在每次迭代时附加新值.
a <- pocket <- 100
while (a > 0) {
if (rbinom(1, 1, 0.5) == 1) {
a <- a + 100
} else {
a <- a - 50
}
pocket <- c(pocket, a)
}
Run Code Online (Sandbox Code Playgroud)
当然,矢量化方法可能更有效,例如:
n <- 1000000
x <- c(100, sample(c(100, -50), n, replace=TRUE))
cumsum(x)[1:match(0, cumsum(x))]
Run Code Online (Sandbox Code Playgroud)
但是不能保证你会在n迭代中耗尽资金(在这种情况下你会收到一个错误,只能看看x实现的轨迹).
编辑
为了回应@Roland所表达的担忧,以下方法避免了在每次迭代时重新分配内存:
n <- 1e6
a <- rep(NA_integer_, n)
a[1] <- 100L # set initial value (integer)
i <- 1 # counter
while(a[i] > 0) {
# first check whether our results will fit. If not, embiggenate `a`.
if(i==length(a)) a <- c(a, rep(NA_integer_, n))
if (rbinom(1, 1, 0.5) == 1) {
a[i+1] <- a[i] + 100L
} else {
a[i+1] <- a[i] - 50L
}
i <- i + 1
}
a[seq_len(i)]
Run Code Online (Sandbox Code Playgroud)