multiple (R) graphs generated in rmarkdown document (knitr block)

I am trying to create some plot shapes in an Rmarkdown document using a loop or lapply.

Script R:

require(plotly) data(iris) b <- lapply(setdiff(names(iris), c("Sepal.Length","Species")), function(x) { plot_ly(iris, x = iris[["Sepal.Length"]], y = iris[[x]], mode = "markers") }) print(b) 

works fine, but doesn't work if included in the knitr block:

 --- output: html_document --- '''{r,results='asis'} require(plotly) data(iris) b <- lapply(setdiff(names(iris), c("Sepal.Length","Species")), function(x) { plot_ly(iris, x = iris[["Sepal.Length"]], y = iris[[x]], mode = "markers") }) print(b) ''' 

I tried replacing print(b) combination of lapply eval and parse but only the last digit was displayed.

I suspect the scope / environment problem, but I cannot find a solution.

+6
source share
2 answers

Instead of print(b) put b in htmltools::tagList() , e.g.

 '''{r} library(plotly) b <- lapply( setdiff(names(iris), c("Sepal.Length","Species")), function(x) { plot_ly(iris, x = iris[["Sepal.Length"]], y = iris[[x]], mode = "markers") } ) htmltools::tagList(b) ''' 

Note. Before Plotly v4, it was necessary to convert Plotly objects to htmlwidgets using the Plotly as.widget() function. Starting with Plotly v4, they are the default htmlwiget objects.

+6
source

I found a dirty solution using a temporary file and knit it:

 ```{r,echo=FALSE} mytempfile<-tempfile() write("```{r graphlist,echo=FALSE}\n",file=mytempfile) write(paste("p[[",1:length(p),"]]"),file=mytempfile,append = TRUE) write("\n```",file=mytempfile,append = TRUE) ``` `r knit_child(mytempfile, quiet=T)` 

But this is unsatisfactory.

+3
source

Source: https://habr.com/ru/post/1242269/


All Articles