Plotting a graph in R and exporting it to Excel in a loop

Viewed 8396

In my data I have multiple countries and each country has 5 products. I performed a regression for each combination and now I am trying to plot the predicted values vs. the actual values on the same graph, for each combination.

I have 10 countries in total and each country has its own tab in an Excel file. Since there are 5 products, this is a total of 50 graphs. I want to plot the graphs in R and export them to Excel in a loop. I am using excel.link package ggplot and the issue that I'm having is that the graphs appear as blank space in Excel or if there was some graph in R - that graph appears instead of the required graph.

**Note: I used to get an error with the first graph that said "rversion not found" but now I updated my RStudio and I no longer get this error. The graph still gets exported blank or the previous graph appears instead

Here is a simplified loop, similar to the one that is in my code. If I run the loop manually, by changing i each time, everything gets exported OK. If I run the for loop, the issues happen that I described above:

require(excel.link)

set.seed(124)

for(i in 1:5){

# i <- 2
myseq <- seq(1,100, by=1)
norm <- rnorm(100)

mydata <- as.data.frame(cbind(myseq, norm))
colnames(mydata)
ggplot(data = mydata, aes(x=myseq, y=norm, group=1)) + geom_line(size=1, col="blue") +
  ggtitle(paste("My Plot ", i))

y.plot=current.graphics()
xl[a1] = list(y.plot)

}

1 Answers
Related