Shiny apps in rmarkdown websites and HTML dependencies - html

I've recently created an rmarkdown website. I now want to have a page that highlights basic Shiny functionality. This is possible using the runtime: shiny option for normal markdown documents. However, when I use this:
---
title: "Untitled"
runtime: shiny
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
inputPanel(
sliderInput("obs", "observations:", min = 10, max = 500, value = 100)
)
renderPlot({hist(rnorm(input$obs), col = 'darkgray', border = 'white')})
```
and try to build the site, I get the following error:
I've made sure all of my packages are up to date.
I get the feeling I may be fundamentally misunderstanding how websites (and Shiny) work, but I can't find an explicit answer to my question in the authoring Shiny document, embedded Shiny page or the rmarkdown website guide.
Is this a case of Shiny apps not being deployable on websites in this fashion at all? Or am I just being dense?
EDIT: output from sessionifo():
> sessionInfo()
R version 3.3.2 (2016-10-31)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Antergos Linux
locale:
[1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
[3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
[5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8
[7] LC_PAPER=en_US.UTF-8 LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
attached base packages:
[1] stats graphics grDevices utils datasets methods base
loaded via a namespace (and not attached):
[1] backports_1.0.5 magrittr_1.5 rprojroot_1.2 htmltools_0.3.5
[5] tools_3.3.2 yaml_2.1.14 Rcpp_0.12.9 stringi_1.1.2
[9] rmarkdown_1.3 knitr_1.15.1 stringr_1.1.0 digest_0.6.12
[13] evaluate_0.10

When you use Shiny controls in r-markdown, you do not embed the application, you embed pieces of the application. For example if you wanted to do that shiny app in r-markdown you would use this code:
---
title: "Untitled"
runtime: shiny
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
inputPanel(
sliderInput("obs", "observations:", min = 10, max = 500, value = 100)
)
renderPlot({hist(rnorm(input$obs), col = 'darkgray', border = 'white')})
```
Which yields this when compiled (and the controls work and the plot updates):

Related

Incorporating Sliders into a Leaflet Map

I was following this tutorial here (https://rstudio.github.io/crosstalk/) and tried to run the code:
library(crosstalk)
library(leaflet)
library(DT)
# Wrap data frame in SharedData
sd <- SharedData$new(quakes[sample(nrow(quakes), 100),])
# Create a filter input
filter_slider("mag", "Magnitude", sd, column=~mag, step=0.1, width=250)
# Use SharedData like a dataframe with Crosstalk-enabled widgets
map = bscols(
leaflet(sd) %>% addTiles() %>% addMarkers(),
datatable(sd, extensions="Scroller", style="bootstrap", class="compact", width="100%",
options=list(deferRender=TRUE, scrollY=300, scroller=TRUE))
)
The map seems to render, but the "interactive slider" does not appear:
Also, I can not seem to save this map:
library(htmlwidgets)
saveWidget(map, "map.html", selfcontained = F, libdir = "lib")
Error in .getNamespace(pkg) :
invalid type/length (symbol/0) in vector allocation
I heard that the slider might require installing some further add-ons, but I have not been able to find out how to do this.
Does anyone know what I can do to resolve this problem?
Thank you!
> sessionInfo()
R version 4.1.3 (2022-03-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 22000)
Matrix products: default
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] DT_0.23 leaflet_2.1.1 crosstalk_1.2.0
loaded via a namespace (and not attached):
[1] jquerylib_0.1.4 pillar_1.7.0 compiler_4.1.3 bslib_0.3.1 tools_4.1.3 digest_0.6.29 lubridate_1.8.0
[8] jsonlite_1.8.0 lifecycle_1.0.1 tibble_3.1.6 pkgconfig_2.0.3 rlang_1.0.2 cli_3.3.0 DBI_1.1.2
[15] yaml_2.3.5 xfun_0.30 fastmap_1.1.0 dplyr_1.0.9 stringr_1.4.0 generics_0.1.3 vctrs_0.4.1
[22] htmlwidgets_1.5.4 sass_0.4.1 hms_1.1.1 tidyselect_1.1.2 glue_1.6.2 R6_2.5.1 fansi_1.0.3
[29] purrr_0.3.4 tidyr_1.2.0 readr_2.1.2 tzdb_0.3.0 magrittr_2.0.2 ellipsis_0.3.2 htmltools_0.5.2
[36] assertthat_0.2.1 utf8_1.2.2 tinytex_0.40 stringi_1.7.6 lazyeval_0.2.2 crayon_1.5.1

Displaying html file using htmltools::tags$iframe in shiny is not working with renderUI()

This is my first question in StackOverflow. Please forgive me if the question is not represented in the proper format.
I have a saved html widget, generated using flowmapblue.R that I want to display in a Markdown Shiny Document.
I am using htmltools::tags$iframe to include the HTML file in the Shiny app. The file is kept under the www directory. For your kind reference, I am sharing the HTML file in the following LINK.
The code that is working and giving desired result is:
---
title: "Flow Map"
author: "xyz"
date: "8/14/2020"
output: html_document
runtime: shiny
---
```{r flowmap, echo=FALSE, message=FALSE, warning=FALSE}
titlePanel("Mobility Flow Map")
mainPanel (htmltools::tags$iframe(src ="June_Spain.html", seamless="seamless", height=600, width="100%"))
```
I am getting this result Result without using renderUI.
But actually my Markdown Shiny document will be responsive where the user can select zones and desired months. Based on those names the relevant HTML file will be selected. That's why I need to use the next following code snippet:
---
title: "Flow Map"
author: "xyz"
date: "8/14/2020"
output: html_document
runtime: shiny
---
```{r flowmap, echo=FALSE, message=FALSE, warning=FALSE}
titlePanel("Mobility Flow Map")
mainPanel(
htmlOutput("display_map")
)
output$display_map <- renderUI({
my_test <- htmltools::tags$iframe(src="June_Spain.html", seamless="seamless", height=600, width="100%")
my_test
})
```
In this case the HTML File is not Found as shown in Result using renderUI.
I checked few similar problems with renderUI() and htmlOutput() but I couldn't make out where it is going wrong. I desperately need your help in this regard. Thanks in advance.
Strange. As a workaround you can encode the HTML to a base64 string:
b64 <- base64enc::dataURI(file = "www/June_Spain.html", mime = "text/html")
output$display_map <- renderUI({
htmltools::tags$iframe(src=b64, height=600, width="100%")
})

Icons do not show up at all in R flexdashboard

Im creating a flexdashboard which displays a table. In the last column icons are included but they are not displayed at all because of flexdashboard. That works normally in shinydashboard. Any workaround?
---
title: "Single Column (Fill)"
output:
flexdashboard::flex_dashboard:
vertical_layout: fill
---
```{r global, include=FALSE}
library(shiny)
library(shinydashboard)
FCB<-c(5,6,4,6,8)
TWI<-c(3,5,2,3,5)
IN<-c(2,1,1,1,1)
DF1<-data.frame(FCB,TWI,IN)
FCB<-c(0,0,1,2,4)
TWI<-c(1,2,3,4,5)
IN<-c(1,3,4,5,6)
DF2<-data.frame(FCB,TWI,IN)
DF1$direction <- ifelse(
DF1$FCB < DF2$FCB,
as.character(icon("angle-up")),
as.character(icon("angle-down"))
)
```
### Chart 1
```{r}
renderTable(DF1, sanitize.text.function = function(x) x)
```
You are using Shiny content rendered to a static file.
I added runtime: shiny to the YAML header.
If you just need arrows would using simpe UTF-8 arrows like these be okay?
If you want to render HTML in a table in flexdashboard you should use a datatable from the DT package. Note that the rendering of the HTML is escaped by default. To render the HTML in your table you have to set escape = FALSE.
Here is an option:
---
title: "Single Column (Fill)"
output:
flexdashboard::flex_dashboard:
vertical_layout: fill
runtime: shiny
---
```{r global, include=FALSE}
library(DT)
library(shiny)
library(shinydashboard)
FCB<-c(5,6,4,6,8)
TWI<-c(3,5,2,3,5)
IN<-c(2,1,1,1,1)
DF1<-data.frame(FCB,TWI,IN)
FCB<-c(0,0,1,2,4)
TWI<-c(1,2,3,4,5)
IN<-c(1,3,4,5,6)
DF2<-data.frame(FCB,TWI,IN)
DF1$direction <- ifelse(
DF1$FCB < DF2$FCB,
"<p>↑</p>",
"<p>↓</p>"
)
DF1.table <- datatable(DF1, escape = FALSE)
```
### Chart 1
```{r}
DT::renderDataTable(DF1.table)
```

Export mermaid chart from DiagrammeR

I'm attempting to export a Gantt chart from mermaid to a file through R. I'd be happy with any file format, but SVG or PNG would be preferable. I'm trying to automate this, so simply pressing export through the GUI is not an option.
Here's my code:
library(DiagrammeR)
graph <- mermaid("
gantt
dateFormat HH:mm:ss.SSS
title Sample Test Gantt
section A
thing1 : 15:58:51.556, 16:05:23.494
section B
thing2 : 16:02:00.391, 16:20:46.533
section C
thing3 : 16:18:57.352, 16:23:10.700
thing4 : 16:24:11.705, 16:30:30.432
")
graph
And the graph it generates:
This is a reported issues with the DiagrammeR package, so you may want to keep an eye on this page for future updates: https://github.com/rich-iannone/DiagrammeR/issues/66
There are two ways this could be done as a workaround:
Using Webshot
An alternative way of saving the file is to use the webshot package. This uses the external dependency phantomjs to convert the HTML widget to an image. It can be setup as follows:
install.packages("webshot")
webshot::install_phantomjs()
Using your above example:
library(DiagrammeR)
library(magrittr)
gannt %>%
htmltools::html_print() %>%
webshot::webshot(file = "gannt.pdf")
This will save the plot as a PDF, but you can create images by changing the filename i.e. gannt.png.
Using the plotly package
The plotly package has a useful function for exporting HTML widgets:
plotly::export(gannt, file = "mermaid.png")
From what I know about mermaid it is not possible yet to export to svg or other formats. But it is possible to dump many mermaid objects to an HTML via Rmd:
---
title: "Untitled"
author: "Me"
date: "August 1, 2018"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document.
```{r echo=FALSE, warning=FALSE, message=FALSE}
library(DiagrammeR)
graph <- mermaid("
gantt
dateFormat HH:mm:ss.SSS
title Sample Test Gantt
section A
thing1 : 15:58:51.556, 16:05:23.494
section B
thing2 : 16:02:00.391, 16:20:46.533
section C
thing3 : 16:18:57.352, 16:23:10.700
thing4 : 16:24:11.705, 16:30:30.432
")
graph
graph
graph
```
It produces an HTML file with all the graphs in it. Not an optimal solution, but better than trying to produce lots of charts manually.
Marked mysteRious' answer as correct, as it really helped. For anyone in the future that runs into the same issue, here's the full solution I used:
Export.Rmd
---
title: "TestingExport"
author: "me"
date: "August 2, 2018"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r echo=FALSE, warning=FALSE, message=FALSE}
library(DiagrammeR)
graph <- mermaid("
gantt
dateFormat HH:mm:ss.SSS
title Sample Test Gantt
section A
thing1 : 15:58:51.556, 16:05:23.494
section B
thing2 : 16:02:00.391, 16:20:46.533
section C
thing3 : 16:18:57.352, 16:23:10.700
thing4 : 16:24:11.705, 16:30:30.432
")
graph
```
Then use the following command to turn this into HTML:
Rscript -e "rmarkdown::render('...\\Export.Rmd')"

How to add table of contents in rmarkdown html Shiny app

Based on this link I tried to include a table of contents in an HTML rmarkdown output. This works fine if I just knit it in RStudio, but when I try the same in Shiny, the table of contents doesn't show up. Am I doing something wrong or is this simply not possible? I also tried some custom css but that also doesn't seem to work. I need this because my users need to set some inputs and download an interactive document themselves with a toc. Please find an example below.
server.r
library(shiny)
library(rmarkdown)
library(htmltools)
library(knitr)
shinyServer(function(input, output) {
output$distPlot <- renderPlot({
# generate bins based on input$bins from ui.R
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)
# draw the histogram with the specified number of bins
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
output$Generate_PDF_Document <- downloadHandler(
# For PDF output, change this to "report.pdf"
filename = paste0("Highchart Document",format(Sys.Date(),"%d%m%Y"),".html"),
content = function(file) {
# # Copy the report file to a temporary directory before processing it, in
# # case we don't have write permissions to the current working dir (which
# # can happen when deployed).
tempReport <- normalizePath('Test.Rmd')
file.copy(tempReport, "Test.Rmd", overwrite = FALSE)
# Knit the document, passing in the `params` list, and eval it in a
# child of the global environment (this isolates the code in the document
# from the code in this app).
out <- render('Test.Rmd', html_document())
file.rename(out,file)
})
})
ui.r
library(shiny)
shinyUI(fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot"),
downloadButton('Generate_PDF_Document','Generate a PDF Report')
)
)
))
rmarkdown doc:
---
title: "Test"
output:
html_document:
toc: true
toc_depth: 3
toc_float: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
Remove html_document() from render. I have not studied the details, but it looks like it forces override of the yaml front matter.