0

我通过以下代码生成了 1000 个模拟。

ar1 = 0.4857
ar2 = 0.0173
ma1 = -0.8054
r0 <-  0.002937432 #mean of margin.logrtn
e0 <- 0.002976873 #mean of fit.margin.logrtn$res


r.sims <- matrix(rep(0,1000*52),nrow=52, ncol=1000)
e.sims <- matrix( rnorm(52*1000, mean =  0.002976873, sd = 0.1056021), 52, 1000) 


r.sims[1] <- ar1*r0 + e.sims[1] + ma1*e0
r.sims[2] <- ar1*r.sims[1] + ar2*r0 + e.sims[2] + ma1*e.sims[1]

for(j in 1:1000) {
    for(i in 1:52) {
        if (i == 1) {
            r.sims[i,] <- r.sims[1]
        } else {
            if(i == 2) {
                r.sims[i,] <- r.sims[2]
            } else {
                if(i > 2) {
                    r.sims[i,] <- r.sims[i-1,]*ar1 + r.sims[i-2,]*ar2 + e.sims[i,] + e.sims[i-1,]*ma1
                }
            }
        }
    }
}

我想在 R 中绘制模拟,我想为模拟创建每周日期并将所有 1000 个模拟绘制在同一张图上。我试图将数据导出到 excel 中并在那里创建日期,然后再次导入数据,但后来我意识到我将不得不创建 1000 个时间序列,这太多了……除非有更简单的方法可以做到这一点…… . 有人可以帮忙吗?

非常感谢!

4

1 回答 1

3

你没有提到什么样的情节所以这里只是一个简单的时间序列情节。无论如何,您也可以在 plot 命令中使用 for 循环,除非我在您的问题中遗漏了某些内容。

ymax <- max(r.sims)
ymin <- min(r.sims)

plot(r.sims[,1], type="l", col="#ff000010", ylim=c(ymin, ymax))
for (i in 2:1000){
lines(r.sims[,i], type="l", col="#ff000010")
}

在此处输入图像描述


编辑:

问:嗨,我想知道是否有任何方法可以绘制多种颜色?非常感谢!

答:是的,您可以通过提供一组颜色代码来做到这一点:

ymax <- max(r.sims)
ymin <- min(r.sims)
color <- c(rep("#ff000010", 499), rep("#0000ff10", 500))

plot(r.sims[,1], type="l", col="#ff000010", ylim=c(ymin, ymax))
for (i in 2:1000){
lines(r.sims[,i], type="l", col=color[i])
}

第三行指定前 499 为红色,接下来的 500 为蓝色。然后在最后一行,添加“col=color[i]”来应用配色方案。

在此处输入图像描述

于 2013-10-15T13:33:27.827 回答