GodinA
GodinA

Reputation: 1093

for loop with a matrix in R

I am trying to code a for loop from a matrix to create a series of plots on a pdf. Here is my code:

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 is a matrix of the following format:

> 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

I first tried this code, which worked fine.

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

I'm sure it's fairly straightforward to fix, but I just can't get my head around it (until now anyway)!

Thank you for your help!

Upvotes: 1

Views: 428

Answers (2)

Tyler Rinker
Tyler Rinker

Reputation: 110072

You could try leaving the quotes off of 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()

or in a more R ish way use:

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)

Upvotes: 3

Justin
Justin

Reputation: 43265

You want the value of the variable i rather than the quoted string "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()

Upvotes: 3

Related Questions