【问题标题】:How to repeat 1000 times this random walk simulation in R?如何在 R 中重复 1000 次这种随机游走模拟?
【发布时间】:2023-03-24 06:39:01
【问题描述】:

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

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]随机游走时间序列进行这种重复?

【问题讨论】:

  • 我同意@Tim - 但我认为这是一个关于堆栈溢出的好问题。我们可以把问题转移到那里吗?

标签: r time-series sampling random-walk


【解决方案1】:

由于y[t] = y[0] + sum epsilon[i],其中sum 取自i=1i=t,序列y[t] 可以立即计算,例如使用R cumsum 函数。重复系列 T=10³ 次就很简单了:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-05
    • 2014-03-26
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多