循环创建错误的图块数量

mar*_*ter 2 plot loops r

我对R很新,并且已经在网上找到了一个解决方案并且没有找到任何可以帮助我的东西.

关于从for循环创建的绘图我有一个问题.我想在3x2网格中创建六个图形,其中所有图形一起显示,其中每个图形都以数据的列标签作为其标题.然而,似乎R不会创建6但是图形数量的两倍,而其中6个具有错误的标题(例如,系列R [,i]而不是DJINDUS).

我的数据集(这是一个名为"R"的矩阵)看起来如下并且有几千行:

         DJINDUS       GSCITOT      NASCOMP       DJTRSPT       DJUTILS     PORTFOLIO
 [1,] -0.0051797207  0.0038918968 -0.014959142 -0.0100216161  0.0025465706 -0.0047444023
 [2,]  0.0103448153 -0.0023765810  0.013946279  0.0164086084  0.0073205395  0.0091287322
 [3,]  0.0038053079 -0.0131512085  0.004045313 -0.0046264989  0.0053159370 -0.0009222299
 [4,]  0.0234136525 -0.0107384963  0.013765670  0.0120004619  0.0099954557  0.0096873488
 [5,] -0.0019038671 -0.0064305092  0.006087090  0.0026823416  0.0046855706  0.0010241253
 [6,]  0.0103801289  0.0012181536  0.009976454  0.0081995006  0.0015569907  0.0062662457
 [7,] -0.0005007307  0.0075137168  0.004886162  0.0041719526 -0.0009155833  0.0030311035
 [8,]  0.0058533353  0.0066382973  0.003438548  0.0047356660  0.0011900949  0.0043711882
 [9,]  0.0058077604  0.0080331085  0.003620382  0.0058304700 -0.0024733215  0.0041636798
[10,] -0.0039335841  0.0120232095  0.006624884  0.0074794664 -0.0043200582  0.0035747834

par(mfcol=c(3,2))

for (i in 1:6){
  ACF.R <-acf(R[,i], lag.max=20, type="correlation", na.action = na.fail)
  header <- colnames(R)[i]
  plot(ACF.R, ci=0.95, type = "h", xlab = "Lag",
       ylab = "ACF", ci.type = "white", main = header)
}
Run Code Online (Sandbox Code Playgroud)

这就是(假)图形输出的样子

在此输入图像描述

请你如此友好地查看我的代码并告诉我问题是什么?

Jil*_*ina 6

只需添加plot=FALSE您的acf电话:

for (i in 1:6){
  ACF.R <-acf(R[,i], lag.max=20, type="correlation", na.action = na.fail, 
              plot=FALSE)
  header <- colnames(R)[i]
  plot(ACF.R, ci=0.95, type = "h", xlab = "Lag",
       ylab = "ACF", ci.type = "white", main = header)
}
Run Code Online (Sandbox Code Playgroud)

这应该产生以下情节:

在此输入图像描述


luk*_*keA 5

默认情况下,每个acf()调用也会打印一个图.添加plot=FALSE以防止它这样做:

labels <- c("DJINDUS","GSCITOT","NASCOMP","DJTRSPT","DJUTILS","PORTFOLIO")
R <- matrix(rnorm(10*length(labels)), nrow=10)
colnames(R) <- labels
par(mfcol=c(3,2))
for (i in 1:6) {
  ACF.R <-acf(R[,i], lag.max=20, type="correlation", na.action = na.fail, plot=FALSE)
  header <- colnames(R)[i]
  plot(ACF.R, ci=0.95, type = "h", xlab = "Lag", ylab = "ACF", ci.type = "white", main = header)
} 
Run Code Online (Sandbox Code Playgroud)