Rmarkdown: Placing static content under a tabbed section - html

I was hoping for help placing static content under a tabbed section in my R markdown file. It's similar to this question: RMarkdown: Tabbed and Untabbed headings, but the solution doesn't account for blank lines in the table of contents.
Is it possible to end the tabbed section without starting a new section? Here's an example:
---
title: "Mtcars Example"
output:
html_document:
toc: true
toc_float: true
number_sections: true
---
# Mtcars Info
The data was extracted from the 1974 Motor Trend US magazine..
# Dataset Prep
No changes were made to the dataset..
# Plots {.tabset .tabset-pills}
```{r results = 'hide', message = FALSE, fig.height = 5, fig.width = 5, echo = FALSE}
plot1 <- ggplot(data = mtcars) +
geom_point(aes(x = mpg, y = hp))
plot2 <- ggplot(data = mtcars) +
geom_point(aes(x = mpg, y = wt))
```
## mpg vs hp
```{r, echo = FALSE}
plot1
```
## mpg vs wt
```{r, echo = FALSE}
plot2
```
#
The plots above show how mpg is related..
# Analysis
the mtcars dataset is a great exploratory dataset to show..
Section 3 is a tabbed section allowing the user to switch between plots. I'd like to have static text underneath it.
The problem is, without starting a new heading, the content is only visible when the 2nd tab is selected. Not good. I can fix this by starting a new heading and putting the content in there.. but now I have a numbered section 4 in my table of contents that's blank. Also not desirable.
Is there any way to fix this? In the Rmarkdown cheatsheet https://www.rstudio.com/wp-content/uploads/2016/03/rmarkdown-cheatsheet-2.0.pdf, you supposedly can end a tabbed section with ###, but that doesn't seem to work either.

I am not sure about any built-in solution. In such cases I usually just go with jQuery. In this case, it is a one-liner.
Reproducible Example:
---
title: "Mtcars Example"
output:
html_document:
number_sections: true
---
<script>
$(document).ready(function() {
$('#myDiv').appendTo('#first-tab-sec');
});
</script>
<div id="myDiv">a
The quick brown fox jumps over the lazy dog.
</div>
# Plots {.tabset .tabset-pills #first-tab-sec}
## mpg vs hp
```{r, echo = FALSE}
plot(mtcars$mpg, mtcars$hp)
```
## mpg vs wt
```{r, echo = FALSE}
plot(mtcars$mpg, mtcars$wt)
```
# Next Section
We created a div element with the id myDiv. Inside that element we store the content, thats supposed to go underneath the tabbed area.
The jQuery (JS) snippet does the following:
As soon as the document finished loading ($(document).ready()), we execute the anonymous function(){...}. Inside that function we grab our div element by its id and append it to the element with the id first-tab-sec.
Multiple Tabbed Sections
If we have another tabbed-section, we just give it a new id, for example second-tab-sec, and add the code
$('#mySecDiv').appendTo('#second-tab-sec');
to the JS chunk. Here we assume that the content is contained within a div with the id mySecDiv.

Related

R: Converting "rmarkdown" to "html" files

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.

Rmarkdown 'saving' an exact place of the html page

I've created two Rmarkdown pages that are linked together. I'd like to know if there is a way to code that the links direct to a specific spot on each page.
---
title: "Page 1"
author: "--"
date: "22 9 2020"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
### Header
example text.
#### example plot 1.
```{r cars}
plot(cars)
```
more example text
#### example plot 2.
```{r pressure, echo=FALSE}
plot(pressure)
```
link to [Page 2](./Page-2.html)
And Page 2:
---
title: "Page 2"
author: "--"
date: "22 9 2020"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
### Header
example text.
#### example plot 1.
```{r cars}
plot(cars)
```
more example text
#### example plot 2.
```{r pressure, echo=FALSE}
plot(pressure)
```
[Page 1](./Page-1.html)
For example, I'd like the page 2 link to redirect straight to the second graph. Moreso, when clicking back to page 1 - is there a way for it to save the spot I was currently looking at?
Thanks.
This feature is not provided for HTML output of rmarkdown/knitr. However, you can easily implement this using javaScript (jquery):
The idea is to include a small script that saves the last scroll position in a variable (I've called it ScrPos below) in local memory and restores the scroll position when the page is (re)loaded.
header.html
<script type="text/javascript">
// check if ScrPos is available. If so, scroll to ScrPos
$(function() {
if (localStorage.ScrPos) {
$(window).scrollTop(localStorage.ScrPos);
}
});
// save last scroll position to ScrPos before page unload
$(window).on("beforeunload", function() {
var ScrPos = $(window).scrollTop();
localStorage.setItem("ScrPos", ScrPos);
});
</script>
You may include header.html in the YAML header (of both) .rmd files like this:
output:
html_document:
include:
in_header: header.html
Note that header.html needs to be in the same directory as the .Rmd.
for the linking to the second graph part it can be easily achieved by using the div id that's used for the second graph, either by explicitly assigning it or by using transforming the spaced section title to a dash separated one `example plot 2.` => id = `example-plot-2.` i.e:
New code for page 2
#### example plot 2.{#second_graph}
```{r pressure, echo=FALSE}
plot(pressure)
```
[Page 1](./Page-1.html)
and then in page one simply add the id to the link i.e:
link to [pressure graph](./Page-2.html#second_graph)

Exclude tabs Rmarkdown based on parameters

I know I can include exclude r code chunks using parameters in Rmarkdown.
http://rmarkdown.rstudio.com/developer_parameterized_reports.html
However how can I exclude or include tabs based on the value of a parameter.
Where a tab is indicated as:
## Header {.tabset}
### Tab 1
content Tab 1
### Tab 2
content Tab 2
##
I'm looking for something like
## Header {.tabset}
### Tab 1
content Tab 1
ifelse(param == False) {
### Tab 2
content Tab 2
}
##
Update
I have some troubles with the answer by StatnMap. Using this code, in the first chunk the HTML after the R chunk is still shown as is the R chunk itself. I could fix this by using a separate eval = FALSE for the R chunk, but I would rather restrict myself to a single parameter in a single chunk. Thus, to only set eval = FALSE in the asis chunk.
## HEADER {.tabset .tabset-pills}
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:
``` {asis, echo = TRUE, eval = FALSE}
### TEST1
```{r echo=FALSE, warning=FALSE}
library(dplyr)
summary(cars)
```
You can also embed plots, for example:
```
### TEST2
```{r, pressure, echo=FALSE}
plot(pressure)
```
You can include your markdown syntax in a asis chunk:
```{asis, echo=TRUE, eval=param}
### Tab 2
content Tab 2
```

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.

On plotting in HTML5 slides with knitr

Here is my problematic slide:
The plain text for this slide is
# Title
```{r plot, echo=FALSE}
library("ggplot2")
x <- seq(-1,1,0.05)
y <- x^3/3-x^2 + rnorm(41,sd=0.1)
qplot(x,y)+geom_smooth()
```
- item 1
- item 2
And I want to:
Hide the comment text (## blahblah)
Hide the text "plot of chunk plot"
Make the plot smaller, so that the items can be shown
Could you please give me some hints? Thank you.
You should take time to read the wonderful documentation provided for knitr.
Without knowing your work flow to create the slides it is hard answer from the html5 end.
You are looking for fig.width, fig.height, fig.cap, warning and message from the knitr chunk options.
```{r plot, echo=FALSE,fig.width = 3, fig.height = 3, fig.cap = '', warning = FALSE, message = FALSE, cache = FALSE}
library("ggplot2")
x <- seq(-1,1,0.05)
y <- x^3/3-x^2 + rnorm(41,sd=0.1)
qplot(x,y)+geom_smooth()
```
- item 1
- item 2
You will have to adjust the height and width to get the size that is suitable for slides