R: Converting "rmarkdown" to "html" files - html

I am using the R programming language. I am trying to recreate the interactive "dashboard" from this website : https://beta.rstudioconnect.com/jjallaire/htmlwidgets-rbokeh-iris/htmlwidgets-rbokeh-iris.html (code is provided on this website).
First, I ran this code to access the "flexdashboard template maker" :
library(flexdashboard)
rmarkdown::draft("dashboard.Rmd", template = "flex_dashboard", package = "flexdashboard")
Then, I deleted all the text in the window that popped up. I copied the R code from the website (https://beta.rstudioconnect.com/jjallaire/htmlwidgets-rbokeh-iris/htmlwidgets-rbokeh-iris.html) into this window and clicked "save":
---
title: "rbokeh iris dataset"
author: "Ryan Hafen"
output:
flexdashboard::flex_dashboard:
orientation: columns
social: menu
source_code: embed
---
```{r setup, include=FALSE}
library(rbokeh)
library(flexdashboard)
```
Column {data-width=600}
-----------------------------------------------------------------------
### Species
```{r}
figure(width = NULL, height = NULL) %>%
ly_points(Sepal.Length, Sepal.Width, data = iris, color = Species)
# figure() %>%
# ly_points(Sepal.Length, Sepal.Width, data = iris,
# color = Species, glyph = Species)
```
Column {data-width=400}
-----------------------------------------------------------------------
### Species (Quantile)
```{r}
figure(width = NULL, height = NULL, legend_location = "top_left") %>%
ly_quantile(Sepal.Length, group = Species, data = iris)
```
### Petal Width
```{r}
figure(width = NULL, height = NULL) %>%
ly_points(Sepal.Length, Sepal.Width, data = iris,
color = Petal.Width)
```
This file ("dashboard.Rmd") is saved in "my documents" (which has been also set to the default working directory):
Now, I want to "view" the dashboard and "save" the dashboard as an ".html" file. I found this other stackoverflow post that shows how to solve this problem: How to convert R Markdown to HTML? I.e., What does "Knit HTML" do in Rstudio 0.96?
I tried to follow the steps in one of the answers provided on this stackoverflow post:
require(knitr) # required for knitting from rmd to md
require(markdown) # required for md to html
markdownToHTML('dashboard.Rmd', 'test.html')
But this produced the following output (incorrect):
Instead of the desired output:
Can someone please show me what I am doing wrong and how can I fix this (i.e. get the desired output) ?
Thanks

After you save the file in dashboard.Rmd, click on Knit -> Knit to flex_dasboard
This opens the dashboard template in RStudio itself. This also automatically creates a HTML file with the same name (dashboard.html) in your working directory.

Related

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%")
})

Looking for a simple way to include profvis output in a Markdown file in R

The title pretty much says it all. I want to profile a function in R (with the profvis package) and display the output in an R Markdown file, without manually creating a screenshot and ideally with no additional packages except the ones that are loaded with profvis, e.g. htmlWidgets and htmltools.
To be more specific I imagine something like:
library(profvis)
profvis_output <- profvis(rnorm(1e06))
htmlwidgets::saveWidget(profvis_output, "provis_output.html")
and then include the thereby created html file in Markdown.
I already tried
htmltools::includeHTML("profvis_output.html")
in the Markdown file but that did not work.
NOTE: I also want it to be renderable to a PDF
This seems to work:
---
title: "Untitled"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(profvis)
```
## profvis
This is an R Markdown document using profvis.
```{r}
profvis({
data(diamonds, package = "ggplot2")
plot(price ~ carat, data = diamonds)
m <- lm(price ~ carat, data = diamonds)
abline(m, col = "red")
})
```

Errors when knitting RMarkdown to HTML (no graphs showing up in the HTML)

Question about knitting RMarkdown.
I am having issues when knitting a Rmarkdown file to HTML/pdf. When I run my chunks of code in the Rmarkdown file everything runs smoothly (and I get my graphs made with ggplot) but when knitting I get an output with no graphs and errors (error in eval, error in ggplot, error in print).
Does anyone have experience with this?
The errors:
Error in eval(lhs, parent): object ‘iso3166’ not found
Error in ggplot(inci_100k, aes(long, lat, map.id=mapname,fill=inci)): object ‘inci_100k’ not found
Error in print(INCIPLOT): object ‘INCIPLOT’ not found
The code:
---
title: "R Markdown MAP"
author: "Alexandra V"
date: "1/4/2020"
output:
html_document: default
pdf_document: default
word_document: default
---
```{r,echo = FALSE, warning = FALSE, message=FALSE, error=TRUE}
knitr::opts_chunk$set(cache=TRUE)
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_chunk$set(error = TRUE)
```
Loading the packages we will need for the following analysis.
```{r echo=FALSE, warning=FALSE}
library(tidyverse)
library(lubridate)
library(ggmap)
library(countrycode)
library(grid)
library(gridExtra)
```
To only keep the data needed to make a worldmap of TB incidences, only the relevant data will be taken from the TB_burden_countries_2020-01-04.csv file. Column 1: country names, column 3: iso3 (country codes), column 6: years, column 8: e_inc_100k (estimated incidence all TB forms per 100.000). To make the file easier to work with the names of the columns will be changed to: country, code, year and inci respectively.
```{r, message=FALSE}
TB.burden <- read.csv("TB_burden_countries_2020-01-04.csv")
TBworldINC.map <- as.data.frame(TB.burden[,c(1,3,6,8)], drop=false)
write.csv(TBworldINC.map, 'TBworldINC.map.csv', row.names = FALSE)
tb.INC <- read_csv("TBworldINC.map.csv") %>%
setNames(c("country", "code", "year", "inci"))
```
```{r}
world <- map_data("world")
tb_some_years <- tb.INC %>%
filter(year %in% c(2005, 2010, 2015, 2018))
inci_100k <- tb_some_years %>%
inner_join(iso3166 %>% select(a3, mapname), by = c(code = "a3")) %>%
left_join(world, by = c(country = "region"))
INCIPLOT <- ggplot(inci_100k, aes(long, lat, map_id = mapname,
fill = inci)) +
geom_map(map = world) +
scale_fill_gradient(low = "blue", high = "yellow") +
theme_void() +
coord_map(xlim = c(-180, 180)) +
labs(fill = "Incidence per year") +
facet_wrap(~ year, ncol = 2)
print(INCIPLOT)
```
picture of the output I get in Rstudio
I have had similar issues when making maps in R. One work around is to create your graphs and to save it locally and including the images. The syntax for adding images in R Markdown is ![alt text](path to image)

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.

Empty Controls and No Plot with rCharts + Rmarkdown + RStudio

I am unable to get a desired HTML from running the code below. I attached the resulting "Output" file as a snapshot. The controls are empty and there is no plot. What am I doing wrong?
Thank you.
Rmarkdown code:
---
title: "Test"
output: html_document
---
```{r, echo=FALSE, results='asis', cache=FALSE}
#install.packages("devtools")
require(devtools)
install_github("ramnathv/rCharts")
install_github("yihui/knitr")
library(rCharts)
library(knitr)
n1 <- rPlot(mpg ~ wt, data = mtcars, color = "gear", type = "point")
n1$addControls("x", value = "wt", values = names(mtcars))
n1$addControls("y", value = "wt", values = names(mtcars))
n1$addControls("color", value = "gear", values = names(mtcars))
n1$show('iframesrc', cdn = TRUE)
```
My setup:
Windows 7 Pro, 64 bit.
RStudio version 0.99.892.
Note to install devtools when running the code attached.
I click on "Knit HTML" in RStudio to build.