0

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.

Anders
  • 73
  • 7
  • I have added the error I get when running the script. – Anders May 04 '20 at 21:35
  • Try remove brackets around `i`. Can you `dput` your data for [reproducible example](https://stackoverflow.com/q/5963269/1422451)? – Parfait May 04 '20 at 21:37
  • Well that was actually it. Removing the brackets from the i gave me four charts. Not the most beautiful ones as the ylim should be very different for each plot it seems... Thank you though. Very much appreciated. – Anders May 04 '20 at 21:56

1 Answers1

0

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

Parfait
  • 104,375
  • 17
  • 94
  • 125