如何在 R 中重复 1000 次这种随机游走模拟? [英] How to repeat 1000 times this random walk simulation in R?

查看:13
本文介绍了如何在 R 中重复 1000 次这种随机游走模拟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm simulating a one-dimensional and symmetric random walk procedure:

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

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

where white noise is denoted by epsilon[t] ~ N(0,1) in time period t. There is no drift in this procedure.

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

Also, RW is symmetric, because Pr(y[i] = +1) = Pr(y[i] = -1) = 0.5.

这是我在 R 中的代码:

Here's my code in 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=5y[1]=0)的概率代码> 和 t=10.)

I would like to simulate 1000 different y[i,t] series (i=1,...,1000; t=1,...,1000). (After that, I will check the probability of getting back to the origin (y[1]=0) at t=3, t=5 and t=10.)

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

Which function would allow me to do this kind of repetition with y[t] random walk time-series?

推荐答案

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

Since y[t] = y[0] + sum epsilon[i], where the sum is taken from i=1 to i=t, the sequence y[t] can be computed at once, using for instance R cumsum function. Repeating the series T=10³ times is then straightforward:

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

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

since each row of y is then a simulated random walk series.

这篇关于如何在 R 中重复 1000 次这种随机游走模拟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆