[英]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}+\varepsilon_t$$
where white noise is denoted by $\\varepsilon_t \\sim N(0,1)$
in time period $t$
. 其中白噪声由时间段
$t$
的$\\varepsilon_t \\sim N(0,1)$
$t$
。 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_{it}$ series (i=1,...,1000;t=1,...,1000)
. 我想模拟1000个不同的
$y_{it}$ 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$.
(在那之后,我将检查在
$t=3$, $t=5$ and $t=10$.
处返回原点($y_1=0$)
的概率$t=3$, $t=5$ and $t=10$.
Which function does allow me to do this kind of repetition with $y_t$
random walk time-series? 哪个函数允许我对
$y_t$
随机游走时间序列进行这种重复?
Try the following: 请尝试以下操作:
length_of_time_series <- 1000
num_replications <- 1000
errors <- matrix(rnorm(length_of_time_series*num_replications),ncol=num_replications)
rw <- apply(errors, 2, cumsum)
This creates 1000 random walks simultaneously by first defining a matrix filled with white noise error terms drawn from a standard normal distribution, and in the second step I calculate the cumulative sums, which should correspond to your random walk, assuming that y_0=0
. 首先定义从标准正态分布得出的填充有白噪声误差项的矩阵,然后同时创建1000个随机游动,然后在第二步中,假设
y_0=0
,则应计算出与随机游动相对应的累计和。
Note that I have ignored that your errors are either -1 or 1, since I am not sure that this is what you intended. 请注意,由于我不确定这是否是您的预期,所以我忽略了您的错误是-1或1。 Having said that, you can adjust the above code easily with the following line to create errors that are either 1 or -1:
话虽如此,您可以使用以下行轻松调整上述代码,以创建1或-1错误:
errors2 <- ifelse(errors > 0, 1, -1)
If you really want to go the way of doing it repeatedly as opposed to doing it simultaneously, you can define a function that returns the random walk, and use replicate
. 如果您真的想重复执行操作而不是同时执行操作,可以定义一个返回随机游走的函数,并使用
replicate
。 Note that you should not hardcode the seed inside the function to avoid replicating the same random walk all the time. 请注意,您不应在函数内部对种子进行硬编码,以避免一直复制相同的随机游走。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.