Search code examples
rhighchartsrchartsioslides

rChart, for loop


I wrote a function to create an rChart on multiple slides using for loops. However calling the function does not create multiple charts. I only get the last chart. This is what my function looks like:

s1Rev <- function(total1){
a <- rCharts:::Highcharts$new()
a$chart(type = "column")
a$xAxis(categories = total1$sources)
a$yAxis(title = list(text = "Revenue"))
a$data(total1)
a$print('chart1', cdn=TRUE, include_assets=TRUE)
}

for(e in 1:length(impEvents)){
  cat("\n\n## Total Revenue: ", eventName[e], "##\n")
  s1Rev(impEvents[e])
}

Once I knit, I see only the last plot on the first slide and nothing on the rest of the slides. What am I doing wrong?


Solution

  • I solved the issue. I only had to change the name (I don't know what the parameter is called) of the chart while in the loop. The code that got me the right results is as follows:

    s1Rev <- function(total1){
        a <- rCharts:::Highcharts$new()
        a$chart(type = "column")
        a$xAxis(categories = total1$sources)
        a$yAxis(title = list(text = "Revenue"))
        a$data(total1)
    return(a)
    }
    
    for(e in 1:length(impEvents)){
      cat("\n\n## Total Revenue: ", eventName[e], "##\n")
      p1 <- s1Rev(impEvents[e])
      p1$print(paste0('chart',e), cdn=TRUE, include_assets=TRUE)
    }