如何在 R 中重复 1000 次随机游走模拟?

How to repeat 1000 times this random walk simulation in R?

我正在模拟一个一维和对称的随机游走过程:

y[t] = y[t-1] + epsilon[t]

其中白噪声在时间段 t 中用 epsilon[t] ~ N(0,1) 表示。此过程中没有漂移。

另外,RW是对称的,因为Pr(y[i] = +1) = Pr(y[i] = -1) = 0.5.

这是我在 R 中的代码:

set.seed(1)
t=1000
epsilon=sample(c(-1,1), t, replace = 1)

y<-c()
y[1]<-0
for (i in 2:t) {
  y[i]<-y[i-1]+epsilon[i]
}
par(mfrow=c(1,2))
plot(1:t, y, type="l", main="Random walk")
outcomes <- sapply(1:1000, function(i) cumsum(y[i]))
hist(outcomes)

我想模拟 1000 个不同的 y[i,t] 系列 (i=1,...,1000; t=1,...,1000)。 (之后我会在t=3t=5t=10处检查回到原点(y[1]=0)的概率。)

哪个函数可以让我用 y[t] 随机游走时间序列进行这种重复?

因为y[t] = y[0] + sum epsilon[i],其中sum取自i=1i=t,序列y[t]可以一次计算,例如使用Rcumsum函数。重复序列 T=10³ 次就很简单了:

N=T=1e3
y=t(apply(matrix(sample(c(-1,1),N*T,rep=TRUE),ncol=T),1,cumsum))

因为 y 的每一行都是一个模拟的随机游走序列。