Add an equation using roxygen2 in Rscript - html

I am using functions described here to render multiple independent R scripts in a single markdown files. But I am not able to include a formatted equation in those scripts. My .Rmd file looks like:
---
title: "My title"
author: "Nacho"
output:
bookdown::html_document2:
base_format: rmdformats::downcute
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
join <- function(ls, sep = ", "){
do.call(paste, append(ls, list(sep = sep)))
}
inline_render <- function(script_name){
suppressMessages(capture.output(rmarkdown::render(paste0(script_name, ".R"),
output_format = "rmarkdown::md_document"), file = "tmp"))
cat(join(readLines(paste0(script_name, ".md")), "\n"))
}
```
Here is some text defining the scope of the analysis...
```{r script, echo=FALSE, results='asis'}
inline_render("script")
```
And in my script I have defined an equation:
#'
#' $$\frac{d_{A}}{dt} = K_{rel}\times A$$
#'
But when this .R is rendered to .md, I get this warning:
[WARNING] Could not convert TeX math \frac{A}{dt} = K_{rel}\times A, rendering as TeX
and this is what is what I find in the .md
$$\\frac{d\_{DXD}}{dt} = K\_{rel}\\times A\_{T-DXd}$$
So, when this is rendered to the final .html I just the plain text ignoring all \*.
I tried to edit the intermediate .md file to remove one of the \ but the one remaining seems to be ignored by the cat() call.
Could anyone help me with this?

Related

Function to create plot and knit to HTML in RMarkdown not working

I have a function in an R Markdown document. The function takes a "case number" variable, which is used to filter some data frames, produce a plot, and output the plot to a knit html document. Here's the basic idea:
---
title: "Plot"
output:
html_document:
toc: true
toc_float: true
toc_depth: 2
---
```{r echo=FALSE, results='hide',message=FALSE,warning=FALSE}
library(dplyr)
library(ggplot2)
library(scales)
library(lubridate)
library(plotly)
library(vistime)
```
```{r echo = FALSE, warning=FALSE, fig.align='CENTER', fig.width=10, fig.height=5}
data <- read.csv(text="event,group,start,end,color
Phase 1,Project,2016-12-22,2016-12-23,#c8e6c9
Phase 2,Project,2016-12-23,2016-12-29,#a5d6a7
Phase 3,Project,2016-12-29,2017-01-06,#fb8c00
Phase 4,Project,2017-01-06,2017-02-02,#DD4B39
Room 334,Team 1,2016-12-22,2016-12-28,#DEEBF7
Room 335,Team 1,2016-12-28,2017-01-05,#C6DBEF
Room 335,Team 1,2017-01-05,2017-01-23,#9ECAE1
Group 1,Team 2,2016-12-22,2016-12-28,#E5F5E0
Group 2,Team 2,2016-12-28,2017-01-23,#C7E9C0
3-200,category 1,2016-12-25,2016-12-25,#1565c0
3-330,category 1,2016-12-25,2016-12-25,#1565c0
3-223,category 1,2016-12-28,2016-12-28,#1565c0
3-225,category 1,2016-12-28,2016-12-28,#1565c0
3-226,category 1,2016-12-28,2016-12-28,#1565c0
3-226,category 1,2017-01-19,2017-01-19,#1565c0
3-330,category 1,2017-01-19,2017-01-19,#1565c0
1-217.0,category 2,2016-12-27,2016-12-27,#90caf9
4-399.7,moon rising,2017-01-13,2017-01-13,#f44336
8-831.0,sundowner drink,2017-01-17,2017-01-17,#8d6e63
9-984.1,birthday party,2016-12-22,2016-12-22,#90a4ae
F01.9,Meetings,2016-12-26,2016-12-26,#e8a735
Z71,Meetings,2017-01-12,2017-01-12,#e8a735
B95.7,Meetings,2017-01-15,2017-01-15,#e8a735
T82.7,Meetings,2017-01-15,2017-01-15,#e8a735")
data <- as.data.frame(data)
#event_id <- "category 1"
build_plot <- function(event_id) {
data.filtered <- data%>%
filter(group==event_id)
p <- vistime(data.filtered)
pb <- plotly_build(p)
pb #Display plot
rmarkdown::render(input = "stack_overflow_example.Rmd",
output_format = "html_document",
output_file = 'stack_overflow_example.html',
output_dir = "//mydir/myfolder")
}
build_plot("category 1")
```
I'm getting this error, and no document is output:
Error in sink(con, split = debug) : sink stack is full
Running render on a document does the same thing as knit to html. That includes running all the R code in the document.
But you shouldn't put render in the document itself - you've created a recursive loop because you call render on the document, which runs the code on the document, which calls render on the document, which runs the code in the document....
Remove the render call from your document, instead put it in a separate R script. Then, running that script will render the document.

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

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.

HTML code inside of a R-markdown block for a single line

I have an R-markdown document in a for loop (testing various kinds of models), and I would like to set them off with HTML Headers, as it is otherwise hard to find the models I am looking for. There is the "asis" option, but that turns off formatting for the entire block, which is not what I want. I have tried a few things I found here, but nothing really works. Here is my code:
---
title: "Untitled"
author: "Mike Wise - 25 Jul 2014"
date: "November 2, 2015"
output: html_document
---
Test
```{r, echo=T}
for (i in 1:3){
print("<h1>Title</h1>")
#print("##Title")
m <- data.frame(matrix(runif(25),5,5))
print(m)
}
```
Here is one try that does not have the right title formatting:
And here is what it looks like with the results="asis" option:
Okay, it is a year and a half later and I still needed this from time to time, but I learned enough since then to know how to do it properly. You need to write a knitr "output hook", and modify the output so the html can "escape" through.
The following accomplishes this:
Added a knitr output hook.
Defined a syntax to specify the needed tag and content
for example to get <h1>some_text</h1> use htmlesc<<(h1,some_text)>>
Figured out a regexp that extracts the h1 and some_text and reformats it as properly tagged html, removing the ## that knitr inserted as well.
Added some more test cases to make sure it did some additional things (like h4, p, proper placement of plots and tables, etc.)
Added another regexp to remove double escaped lines which was adding some unwanted whitespace paneled constructs.
So here is the code:
---
title: "Output Hook for HTML Escape"
author: "Someone"
date: "2017 M04 25"
output:
html_document:
keep_md: true
---
```{r setup, include=T,echo=TRUE}
knitr::opts_chunk$set(echo = TRUE)
hook_output <- knitr::knit_hooks$get("output")
knitr::knit_hooks$set(output=function(x,options){
xn <- hook_output(x,options)
# interestingly xn is a big character string.
# I had expected a list or vector, but the length of x is 1 and the class is character.
# The following regexp extracts the parameters from a statement of the form
# htmlesc<<(pat1,pat2)>> and converts it to <pat1>pat2</pat1>
xn <- gsub("## htmlesc<<([^,]*),{1}([^>>]*)>>","\n```\n<\\1>\\2</\\1>\n```\n",xn)
# now remove double escaped lines that occur when we do these right after each other
gsub(">\n```\n\n\n```\n<",">\n<",xn)
}
)
```
## An analysis loop in a single R chunk with R Markdown
In the following, we do a loop and generate 3 sets of data:
(#) We have some explanitory text
(#) then we do a bar plot with ggplot
(#) then we print out a table
(#) then we do a base plot - just for fun
```{r, echo=T, fig.height=3,fig.width=5}
library(knitr)
library(tidyr)
library(ggplot2)
set.seed(123)
for (i in 1:3){
mdf <- data.frame(matrix(runif(25),5,5))
cat(sprintf("htmlesc<<h1,Title %d>>\n",i))
cat(sprintf("htmlesc<<h4,Smaller Title - also for %d>>\n",i))
cat(sprintf("htmlesc<<p,and some text talking about this %d example>>\n",i))
print(sapply(mdf,mean))
gdf <- gather(mdf,series,val)
gp <- ggplot(gdf)+geom_bar(aes(series,val,fill=series,color=I("black")),stat="identity")
print(gp)
print(mdf)
plot(mdf)
}
```
And this is the output (shrunk a bit as you don't need the details).
The only real docs for this by the way are Yihui's excellent knitr book, a search finds it easily.
You could try using the kable function:
```{r, echo=T, results="asis"}
library(knitr)
for (i in 1:3){
print("<h1>Title</h1>")
#print("##Title")
m <- data.frame(matrix(runif(25),5,5))
print(kable(m, format = "html"))
}
```
Which gives me:
Try this one.
```{r, echo=F, results="asis"}
for (i in 1:3){
library(knitr)
print("<h1>Title</h1>")
#print("##Title")
m1 <- knitr::kable(data.frame(matrix(runif(25),5,5)))
print(m1)
}
```