[英]How to repeat 1000 times this random walk simulation in R?
I'm simulating a one-dimensional and symmetric random walk procedure: 我正在模拟一维对称的随机游走过程:
y[t] = y[t-1] + epsilon[t]
where white noise is denoted by epsilon[t] ~ N(0,1)
in time period t
. 其中白噪声在时间段
t
由epsilon[t] ~ N(0,1)
。 There is no drift in this procedure. 这个过程没有任何偏差。
Also, RW is symmetric, because Pr(y[i] = +1) = Pr(y[i] = -1) = 0.5
. 此外,RW是对称的,因为
Pr(y[i] = +1) = Pr(y[i] = -1) = 0.5
。
Here's my code in R: 这是我在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)
I would like to simulate 1000 different y[i,t]
series ( i=1,...,1000; t=1,...,1000
). 我想模拟1000个不同的
y[i,t]
系列( 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
.) (之后,我将检查在
t=3
, t=5
和t=10
返回原点的概率( y[1]=0
)。)
Which function would allow me to do this kind of repetition with y[t]
random walk time-series? 哪个函数可以让我用
y[t]
随机游走时间序列进行这种重复?
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. 由于
y[t] = y[0] + sum epsilon[i]
,其中sum
从i=1
到i=t
,所以可以使用例如R cumsum
函数一次计算序列y[t]
。 Repeating the series T=10³ times is then straightforward: 然后重复T =10³次系列是很简单的:
N=T=1e3
y=t(apply(matrix(sample(c(-1,1),N*T,rep=TRUE),ncol=T),1,cumsum))
since each row of y
is then a simulated random walk series. 因为
y
每一行都是模拟的随机游走系列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.