1

I have created a function that programmatically generates the necessary charts for a pre-modeling Data Review.

My goal is to run these in R Markdown to create a presentation, however, when I attempt to create an html_document, slidy_presentation, or ioslides_presentation, they don't render in the output.

See function code (the function works when running in RStudio):

data_review<- function(df, dateVar, depVar, indVars){
  for (i in indVars){
    scale_factor<- max(df[depVar])/max(df[i])
    cols <- c("Dependent" = "skyblue", "Independent" = "black")
    print(plotly::ggplotly(ggplot2::ggplot(df, ggplot2::aes(x= !!as.name(dateVar))) +
                         ggplot2::geom_line(ggplot2::aes(y= !!as.name(depVar), color= 'Dependent')) +
                         ggplot2::geom_line(ggplot2::aes(y= !!as.name(i)*scale_factor, color= "Independent")) +
                         ggplot2::scale_colour_manual(name= 'Variables', values=cols) +
                         ggplot2::ylab(depVar) +
                         ggplot2::xlab(toupper(dateVar)) +
                         ggplot2::ggtitle(label = paste(depVar, 'vs.', i, sep = ' '))))
  }
}

And the corresponding data:

df<- data.frame(date= seq(as.Date('2019-01-01'),as.Date('2019-01-10'),'days'), 
                sales= rnorm(n = 10, mean = 5, sd = 1),
                y1= rnorm(n = 10, mean = 6, sd = 2), 
                y2= rnorm(n = 10, mean = 3, sd = 1),
                y3= rnorm(n = 10, mean = 5, sd = 1)
                )

Run in Studio

data_review(df = df, dateVar = 'date', depVar = 'sales', indVars = c('y1', 'y2', 'y3'))

<code>data_review</code> output

Run in R Markdown (slidy_presentation example)

No charts render, only the code: output in r markdown

How can I get plots to render?

dre
  • 474
  • 5
  • 19

1 Answers1

1

Does this work for the data_review function in creating an html document?

data_review<- function(df, dateVar, depVar, indVars){
  plotlist = list()
  for (i in indVars){
    scale_factor<- max(df[depVar])/max(df[i])
    cols <- c("Dependent" = "skyblue", "Independent" = "black")
    p <- ggplot2::ggplot(df, ggplot2::aes(x= !!as.name(dateVar))) +
                             ggplot2::geom_line(ggplot2::aes(y= !!as.name(depVar), color= 'Dependent')) +
                             ggplot2::geom_line(ggplot2::aes(y= !!as.name(i)*scale_factor, color= "Independent")) +
                             ggplot2::scale_colour_manual(name= 'Variables', values=cols) +
                             ggplot2::ylab(depVar) +
                             ggplot2::xlab(toupper(dateVar)) +
                             ggplot2::ggtitle(label = paste(depVar, 'vs.', i, sep = ' '))
    plotlist[[i]] = plotly::ggplotly(p)
  }
  htmltools::tagList(setNames(plotlist, NULL))
}
Ben
  • 28,684
  • 5
  • 23
  • 45
  • thanks @ben! in an ideal world, we could render each chart on it's own slide and use `.md` to write headers, but that's the next phase! – dre Jun 06 '19 at 17:39