0

My goal is to create a loop that iterates through several variables and plots a graph for each of them before saving them to a pdf file. Every page needs to have a single graph and one page needs to have all of them in the same graph.

My variables are: y1, y2, y3, and y4. They are stored in yieldcurves <-c(y1, y2, y3, y4). The variables all have a date and a value, like shown below:

date: 2018-04-26 last_price: 2.8310

Furthermore I have converted the dataframe to long data, using 'reshape'.

yieldcurves.long<-reshape(yieldcurves,
    varying = c("y1", "y2","y3", "y4"), 
    direction = "long", idvar = "caseid", sep = "_", timevar = "maturity")
names(yieldcurves.long) <-c("date", "maturity", "yield", "subject")

Now I want to create the loop. I have tried the code below:

pdf("yieldcurves", onefile = TRUE)
nr_yc <-length(unique(yieldcurves.long$maturity))
yc<-list(unique(yieldcurves.long$maturity))

for (i in 1:yc){
  Dataplot<-subset(yieldcurves.long, yieldcurves.long$maturity==nr_yc[[1]][i])
  myplot<-ggplot(Dataplot) + geom_line(aes(x=yieldcurves.long$date,
    y= yieldcurves.long$yield))+ 
    labs(x ="Year", y = "Yield (%)")
 grid.arrange(myplot)
}
dev.off()

Unfortunately, this does not work. Do you know what I'm doing wrong? Thanks a lot!

Mark
  • 3
  • 2
  • 1
    Provide us with some data to work with. I'm having trouble understanding what your data set looks like. – LetEpsilonBeLessThanZero Apr 26 '18 at 13:35
  • 1
    Possible duplicate of [R: saving multiple ggplots using a for loop](https://stackoverflow.com/questions/26034177/r-saving-multiple-ggplots-using-a-for-loop) – camille Apr 26 '18 at 16:52

0 Answers0