Frank Harrell
Frank Harrell

Reputation: 2230

How to write an R function that creates a series of plotly plots interspersed with markdown

I have a function that generates a variable number of plotly graphics and creates R markdown headers such as

### Caption for plot

These headers ultimately appear in a floating table of contents in an R markdown html report produced under RStudio.

I know how to use htmltools::tagList to produce a sequence of html and plotly objects that will render all in one stream, but I don't see how to substitute markdown for the htmltools::HTML('foo') piece of an htmltools::tagList(list(plot_ly(...), HTML('caption stuff), ...)) element.

Upvotes: 2

Views: 661

Answers (1)

Frank Harrell
Frank Harrell

Reputation: 2230

Thanks to r2evans here is a solution for my problem. Here R is a list of character vectors, each element of which is a mixture of text and markdown. Pl is a list of plotly objects. nP is the length of each list.

bn <- paste0('c', round(runif(1, 0, 1e6)))  # base chunk name
for(i in 1 : nP) {
  cn <- paste0(bn, i)  # name of individual generated chunk
  Plti <- Pl[[i]]      # fetch i'th plotly graphic object
  k <- c(R[[i]], paste0('```{r ', cn, ',echo=FALSE}'), 'Plti', '```')
  cat(trimws(knitr::knit(text=knitr::knit_expand(text=k), quiet=TRUE)))
  }
}

Upvotes: 2

Related Questions