Search code examples
rloopsplotxts

R loop xts plots


I am stuck on what is probably a simple problem: Loop on xts objects.

I would like to make four different plots for the elements in the basket: basket <- cbind(AAPLG, GEG, SPYG, WMTG)

> head(basket)
           new.close new.close.1 new.close.2 new.close.3
2000-01-04 1.0000000   1.0000000   1.0000000   1.0000000
2000-01-05 1.0146341   0.9982639   1.0017889   0.9766755
2000-01-06 0.9268293   1.0115972   0.9856887   0.9903592
2000-01-07 0.9707317   1.0507639   1.0429338   1.0651532
2000-01-10 0.9536585   1.0503472   1.0465116   1.0457161
2000-01-11 0.9048780   1.0520833   1.0339893   1.0301664

This is my idea so far, as I cannot simply put in i as column name:

   tickers <- c("AAPLG", "GEG", "SPYG", "WMTG")

par(mfrow=c(2,2))    
for (i in 1:4){
    print(plot(x = basket[, [i]], xlab = "Time", ylab = "Cumulative Return",
         main = "Cumulative Returns", ylim = c(0.0, 3.5), major.ticks= "years",
         minor.ticks = FALSE, col = "red"))
    }

This is the error I get when running the script:

Error: unexpected ',' in "     main = "Cumulative Returns","
>      minor.ticks = FALSE, col = "red"))
Error: unexpected ',' in "     minor.ticks = FALSE,"
> }
Error: unexpected '}' in "}"

Any help is very much appreciated.


Solution

  • As mentioned, remove the square brackets around i:

    par(mfrow=c(2,2))    
    for (i in 1:4){
        print(plot(x = basket[, i], xlab = "Time", ylab = "Cumulative Return",
             main = "Cumulative Returns", ylim = c(0.0, 3.5), major.ticks= "years",
             minor.ticks = FALSE, col = "red"))
    }
    

    But even better, assign names with cbind in building xts object or re-name your xts object like any data frame, then iterate across names for column referencing and titles:

    Plot

    # PASS NAMES WITH cbind
    basket <- cbind(AAPLG=APPLG, GEG=GEG, SPYG=SPYG, WMTG=WMTG)
    
    # RENAME AFTER cbind
    # basket <- cbind(AAPLG, GEG, SPYG, WMTG)
    # colnames(basket) <- c("AAPLG", "GEG", "SPYG", "WMTG")
    
    par(mfrow=c(2,2))
    sapply(names(basket), function(col)
      print(plot(x = basket[, col], xlab = "Time", ylab = "Cumulative Return", data = basket,
                 main = paste(col, "Cumulative Returns"), ylim = c(0.0, 3.5), 
                 major.ticks= "years", minor.ticks = FALSE, col = "red"))
    )
    

    Plot Output