1

我正在尝试从矩阵编写 for 循环以在 pdf 上创建一系列图。这是我的代码:

pdf("/Users/Aurelz/Documents/Shark Research/DFO-data/Arctic/plots.pdf", height=8, width=6.5)
par(mfrow=c(3,2), mar=c(0.8,0.8,0.8,0.8), oma=c(2,2,1,1.5), mgp=c(0.5,0.5,0))

for (i in c("JUL","AUG","SEPT","OCT","NOV","DEC")){
  plot(Thorny.Lmm[["r","i"]], Thorny.Lmm[["Lmm","i"]], type="l")
  abline(h=0, lty=2) 
  title(main="Thorny skate in i")
}
dev.off()

>Error in Thorny.Lmm[["r", "i"]] : subscript out of bounds

Thorny.Lmm 是以下格式的矩阵:

> Thorny.Lmm
    JUL         AUG         SEPT        OCT         NOV         DEC        
r   Numeric,513 Numeric,513 Numeric,513 Numeric,513 Numeric,513 Numeric,513
Kmm Numeric,513 Numeric,513 Numeric,513 Numeric,513 Numeric,513 Numeric,513
Lmm Numeric,513 Numeric,513 Numeric,513 Numeric,513 Numeric,513 Numeric,513

我首先尝试了这段代码,效果很好。

plot(Thorny.Lmm[["r","JUL"]], Thorny.Lmm[["Lmm","JUL"]], type="l")
abline(h=0, lty=2)
title(main="Thorny JUL")

我确信修复它相当简单,但我就是无法理解它(无论如何直到现在)!

感谢您的帮助!

4

2 回答 2

3

您想要变量的值i而不是引用的字符串"i"

for (i in c("JUL","AUG","SEPT","OCT","NOV","DEC")){
  plot(Thorny.Lmm[["r",i]], Thorny.Lmm[["Lmm",i]], type="l")
  abline(h=0, lty=2) 
  title(main=paste("Thorny skate in", i))
}
dev.off()
于 2012-04-12T18:48:27.337 回答
3

您可以尝试将引号从 i 中去掉:

for (i in c("JUL","AUG","SEPT","OCT","NOV","DEC")){
  plot(Thorny.Lmm[["r",i]], Thorny.Lmm[["Lmm", i]], type="l")
  abline(h=0, lty=2) 
  title(main=paste("Thorny skate in", i))
}
dev.off()

或者以更 R ish 的方式使用:

plotter <- function(month){
    plot(Thorny.Lmm[["r",month]], Thorny.Lmm[["Lmm",month]], type="l")
    abline(h=0, lty=2)
    title(main=paste("Thorny" month))
}

lapply(colnames(Thorny.Lmm), plotter)
于 2012-04-12T18:52:47.807 回答