循环创建错误的图块数量

时间:2013-12-29 15:58:43

标签: r loops plot

我对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)
}

这是(假)图形输出looks like

的方式

enter image description here

请您检查我的代码并告诉我问题是什么?

2 个答案:

答案 0 :(得分: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)
}

这应该产生以下情节:

enter image description here

答案 1 :(得分: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)
}