Evaluate html script stored in R object in R-markdown - html

In Rmarkdown, how can I implement/evaluate some HTML code stored in an R character object?
If I explicitly paste the code as plain text, it works as expected e.g. <details><summary>Show/hide.</summary>SomeText</details>.
However, I need to evaluate this from an R object; e.g. how to evaluate the content of the Text object: Text <- '<details><summary>Show/hide.</summary>SomeText</details>'?
Below is a reprex.
Thanks, Ahmed
---
title: "Literature notes"
output:
html_document:
#code_folding: hide
---
<details><summary>Show/hide.</summary>SomeText</details> # This works
```{r, eval=TRUE, echo=F}
Text <- '<details><summary>Show/hide.</summary>SomeText</details>'
Text
## how to do the same using info stored in 'Text' object
```

You can use results='asis' in the code chunk:
---
title: "Literature notes"
output:
html_document:
#code_folding: hide
---
```{r, eval=TRUE, echo=F, results='asis'}
Text <- '<details><summary>Show/hide.</summary>SomeText</details>'
cat(Text)
``

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

Links in RMarkdown Datatable

I'm trying to create active links in an RMarkdown document. In the code below, the basic kable table is perfect, but the datatable version turns the links into text
---
title: "Example"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(knitr)
library(DT)
example.df <- data.frame("link"=c("[Tokyo](https://en.wikipedia.org/wiki/Tokyo)","[Paris](https://en.wikipedia.org/wiki/Paris)"), "country"=c("Japan","France"))
kable(example.df)
datatable(example.df)
Whoops, here's the answer: format the links as raw HTML not as RMarkdown syntax http://blogs.oregonstate.edu/cgrb/2019/08/06/r-tips-a-table-makeover-with-dt/
There are 2 changes needed to it to work with datatable.
Format the links as raw HTML, not Markdown
Include relevant escape arguments as to NOT escape the link column. For simplicity in this example, we use escape=FALSE
Here is a full reprex answer.
---
title: "Example"
output: html_document
---
```{r setup, include=TRUE}
knitr::opts_chunk$set(echo = TRUE)
library(knitr)
library(DT)
example.df.kable <- data.frame("link"=c("[Tokyo](https://en.wikipedia.org/wiki/Tokyo)","[Paris](https://en.wikipedia.org/wiki/Paris)"), "country"=c("Japan","France"))
example.df.datatable <- data.frame("link"=c(
'Tokyo',
'Paris'),
"country"=c("Japan","France"))
kable(example.df.kable)
datatable(example.df.kable) # This does NOT show the links
datatable(example.df.datatable) # This does NOT show the links
datatable(example.df.datatable, escape=FALSE) # This does show the links

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

Knitr, RMarkdown: How to have Latex page break omitted in HTML Output

I have an RMarkdown file that I want to publish to both HTML and PDF. I use a page break command, \newpage, in the file to insert a page break in the PDF output. However, in the HTML output, the \newpage shows up as part of the content.
How do I get knitr/pandoc to omit the \newpage from the HTML output?
I tried embedding the \newpage in an HTML comment, but then it had no effect in the PDF output.
Here is the Rmd file.
---
title: 'RMarkdown Test'
author: "Carl Parker"
date: "July 16, 2017"
output:
pdf_document: default
html_document:
keep_md: yes
---
# Page 1 #
\newpage
# Page 2 #
**--- END ---**
Here is the code that builds/renders.
library( "rmarkdown" )
library( "knitr" )
render( "test-1.rmd", output_format = "all" )
# --- END ---
If you want that a code execute only for pdf and not for html, you may use function knitr::pandoc_to() as follows. You can also use it to write some text only for html or for pdf:
Be careful with \, it needs to be doubled \\ when called in a paste or cat inside a R code.
---
title: "RMarkdown Test"
author: "Carl Parker"
date: "July 16, 2017"
output:
html_document:
keep_md: yes
pdf_document: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# Page 1 #
<!-- use newpage for latex only -->
`r if(knitr:::pandoc_to() == "latex") {paste("\\newpage")}`
<!-- Specific text for html or pdf -->
`r ifelse(knitr:::pandoc_to() == "html", "Text in html output only", "Text in pdf output only")`
# Page 2 #
**--- END ---**

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