R Notebook HTML Format - add hyperlinks to paged table - r

I wish to knit an html file from an R Notebook that contains paged tables with hyperlinks.
Hyperlinks can be inserted using knitr::kable, but I can't find a way to generate a paged table with this function.
Paged tables are the default notebook output, but I can't find a way of inserting functional hyperlinks. Many thanks for your help.
---
title: "Paged notebook table with hyperlinks"
output:
html_notebook:
code_folding: "hide"
---
```{r rows.print=3}
wiki.url <- "https://en.wikipedia.org/wiki/"
df1 <- data.frame(Month=month.name, URL=paste0("[", month.name, "](", wiki.url, month.name, ")"))
df2 <- data.frame(Month=month.name, URL=paste0("<a href='", wiki.url, month.name, "'>", month.name, "</a>"))
print(df1)
```
```{r rows.print=3}
print(df2)
```
```{r rows.print=3}
knitr::kable(df1)
```
```{r rows.print=3}
knitr::kable(df2)
```

Since there doesn't seem to be a perfect solution to my problem, I thought I'd post the workaround that I came up with - in case someone has a similar problem.
I created the table plus hyperlinks with knitr::kable and then added an html button and inline javascript to toggle visibility - not as elegant as a paged table, but does the job.
Note the <script> tag at the bottom of the file that hides tables by default.
(Paste code into an .Rmd file in RStudio):
---
title: "Managing large tables with hyperlinks in html notebook"
output:
html_notebook:
code_folding: "hide"
---
<script>
function myFunction(id) {
var x = document.getElementById(id);
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
</script>
```{r}
library(knitr)
df1 <- data.frame(Month=month.name, Link=paste0("[", month.name, "](https://en.wikipedia.org/wiki/", month.name, ")"))
```
<button class="button" onclick="myFunction('DIV_months')">Show/hide table</button>
<div id="DIV_months" class="div_default_hide">
```{r}
knitr::kable(df1)
```
</div>
<script>
var divsToHide = document.getElementsByClassName("div_default_hide");
for(var i = 0; i < divsToHide.length; i++)
{
divsToHide[i].style.display = 'none';
}
</script>

Related

CSS selector for font color in flextable with shadow host on

I'm unsuccessfully trying to set the font color for flextable generated in r markdown using a css stylesheet.
I can accomplish this when I turn off shadow host, but not with it on. (Just turning it off removes other desirable features.) Here's a short r markdown file demonstrating the difference.
---
title: "Untitled"
output: html_document
---
<style>
div.flextable-shadow-host * {
color: pink;
}
div.tabwid * {
color: pink;
}
</style>
# ignores CSS above
```{r, echo=FALSE}
library(flextable)
flextable(head(mtcars))
```
# accepts CSS above
```{r, echo=FALSE}
ft <- flextable(head(mtcars))
htmltools_value(ft, ft.shadow = FALSE)
```
I want the css external to the r code because I have a button selector on the website the user can change the overall style (e.g., dark mode or not).
When using shadow, the table is assembled outside of HTML. Only the id connects the table to HTML. However, flextable has functions for setting the color. Why not just use one of the many built-in methods to change the color?
For example:
# ignores CSS above
```{r liberator,include=F}
library(flextable)
library(tidyverse)
```
```{r tbler, echo=FALSE}
flextable(head(mtcars)) %>%
color(color = "pink", part = "all")
```
# accepts CSS above
```{r, echo=FALSE}
ft <- flextable(head(mtcars))
htmltools_value(ft, ft.shadow = FALSE)
```
There are many things you can do with flextable styling. You can see more customization options here.
Update: Based on your comments
Okay, this works to change the color of a flextable.
This works if there is only one flextable in the script.
I have the color of the text set to #b21E29 (a shade of red). You can change that as you see fit.
These will SKIP non-shadow flextables
Add this chunk anywhere in your RMD script. This requires no additional libraries or any other customization in your R code.
```{r js_ing,results="asis",engine="js",echo=F}
// extract the styles that are set for the flextable
letMe = document.querySelector('div.flextable-shadow-host').shadowRoot.querySelector('div>style');
// replace color style
// preceding ';' so that 'background-color' doesn't change
letMe.innerHTML = letMe.innerHTML.replace(/;(color:.+?);/g, ';color:#b21e29 !important;');
```
If you have more than one flextable with shadow on, you can use one of the two following chunks instead. In the first--all the same color; in the second--each table has a different color.
These work if there is more than one flextable in the script.
Pay attention to the comments so you can see what to use when depending on your desired output.
All the same color:
```{r moreJs_ing,results="asis",engine="js",echo=F}
// collect all of the flextables with shadow
letMe = document.querySelectorAll('div.flextable-shadow-host');
// to set all shadow flextables to the same font color:
for(i = 0, n = letMe.length; i < n; i++){
showMe = letMe[i].shadowRoot.querySelector('div>style');
showMe.innerHTML = showMe.innerHTML.replace(/;(color:.+?);/g, ';color:#b21e29 !important;');
}
```
Each with there own color:
```{r evenMoreJs_ing,results="asis",engine="js",echo=F}
//alternatively to set each to a different color
// make sure you only include one of these options!
// collect all of the flextables with shadow
letMe = document.querySelectorAll('div.flextable-shadow-host');
// first table in script
showFirst = letMe[0].shadowRoot.querySelector('div>style');
showFirst.innerHTML = showFirst.innerHTML.replace(/;(color:.+?);/g, ';color:#b21e29 !important;');
// second table in script
showSecond = letMe[1].shadowRoot.querySelector('div>style');
showSecond.innerHTML = showSecond.innerHTML.replace(/;(color:.+?);/g, ';color:#003b70 !important;');
// change the indices for each table, keep in mind the first table is [0], not [1]
```
If you aren't sure where you want to go with these, add all three and and include=F as a chunk option to the two you aren't using at that moment in time.

how to include blocks that appear and disappear in html using css

I am using bookdown (html) instead of slides in lectures. I really would like to create blocks that appear/disappear to include questions` solutions.
Probably I can do it by css. But I do not now how to do this and also include my css without mess with the bookdown css
Example:
Question: bla bla bla ?
Solution uncover
When I click in uncover I could show my R code and output.
That would be great :)
You can achieve what you want through the knitr hooks. When you set a hook option for code chunk (in this example uncover = TRUE), it will trigger the corresponding hook function uncover, and the hook can write something before and after the html code generated from the chunk output.
In the code below, I first define a Javascript function function uncover(id) which can uncover certain html element by id. And I let the hook uncover to generate a html button which calls the Javascript function before the chunk output and wrap the output with a div with certain id and style.display =none`. You can make modification to the code below to adapt to your need, but the idea is like this.
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
uncover <- function(before, options, envir) {
if (before) {
id <- options$id
button_string <- paste0("<button onclick=\"uncover('",
id,
"')\">Uncover</button>")
div_string <- paste0("<div id = '", id,
"', style = 'display:none'>")
paste0(button_string, "\n", div_string)
}
else {
"</div>"
}
}
knitr::knit_hooks$set(uncover = uncover)
```
<script>
function uncover(id) {
var x = document.getElementById(id);
x.style.display = 'block';
}
</script>
```{r, uncover = TRUE, id = "script"}
1 + 1
```
Edit at 05/03/2020
Currently, knitr or pandoc or something else in the toolchain refuses to convert invisible markdown elements into valid HTML, so the solution above does not work perfectly. One solution is to make all the things visible at first, but provide a button to hide them like the following:
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
uncover <- function(before, options, envir) {
if (before) {
id <- options$id
button_string <- paste0("<button onclick=\"uncover('",
id,
"')\">Uncover</button>")
div_string <- paste0("<div id = '", id,
"' class = 'cover'>")
paste0(button_string, "\n", div_string)
}
else {
"</div>"
}
}
knitr::knit_hooks$set(uncover = uncover)
```
```{r, uncover = TRUE, id = "script"}
1 + 1
```
<script>
function uncover(id) {
var x = document.getElementById(id);
x.style.display = 'block';
}
function cover() {
var xs = document.getElementsByClassName('cover');
for(count = 0; count < xs.length; count++) {
xs[count].style.display = 'none';
}
}
</script>
<button onclick="cover()">Cover all</button>

R flexdashboard remove title bar

I am working on a project using rMarkdown and the flexdashboard package from rStudio. Everything is coming together nicely. But I would like to remove the blue title bar you see at the top of the image here.
We are dropping this html page into a window so it becomes a second title bar, which looks terrible. Is there a function in flexdashboard to remove this entire apparatus?
Here is the YAML and the first chunk you see just below the blue bar in the photograph. Any suggestion would be greatly appreciated.
---
title: New Hampshire Statewide Age Adjusted Incedence Rates of Lyme
output:
flexdashboard::flex_dashboard:
orientation: rows
---
```{r setup, include=FALSE, message=FALSE, warning=FALSE, echo=TRUE}
```
Row
-----------------------------------------------------------------------
###
```{r, aarState, message=FALSE, warning=FALSE}
library(flexdashboard)
library(rbokeh)
#load state-wide age adjusted rates
aar<-read.csv("stateAAR.csv")
figure(title=" Age Adjusted Rates by Year",width= 1500, height =600) %>%
ly_segments(year, lci*100000, year, uci*100000, data=aar, color = "#b37700", width = 1) %>%
ly_points(year, adj.rate*100000, glyph = 21, size=6, data = aar, hover= "<strong>Rate per 100,000:</strong> #rateHundThou </br> <strong>Upper Confidence:</strong> #uciHT </br><strong> Lower Confidence:</strong> #lciHT " , color="#666622" )%>%
x_axis(label ='Year')%>%
y_axis(label ='Age Adjusted Rate')
```
Row
You can just add CSS styling directly to your markdown document (no JQuery required):
---
title: "Untitled"
output:
flexdashboard::flex_dashboard:
orientation: columns
vertical_layout: fill
---
<style>
body {
padding-top:0px
}
.navbar{
visibility: hidden
}
</style>
```{r setup, include=FALSE}
library(flexdashboard)
```
Column {data-width=650}
-----------------------------------------------------------------------
### Chart A
```{r}
hist(iris$Sepal.Length)
```
Column {data-width=350}
-----------------------------------------------------------------------
### Chart B
```{r}
hist(iris$Sepal.Width)
```
### Chart C
```{r}
hist(iris$Petal.Length)
```
Results in:
I am not aware of any flexdashboard option. But you could use jQuery to remove the navbar and move the body up. Just include the following snippet right after your YAML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('.navbar').remove();
$('body').css('padding-top', '0px');
});
</script>
I think this leaves the main navigation bar of the parent document untouched. If not it might need some lsight modification.

Centering pander tables

I am using pander in my Rmarkdown document to display tables. Is there away to center the table?
I have tried a few different methods, but none of them seem to work. For example:
{r, fig.align="center"}
library(pander)
test <- as.data.frame(matrix(ncol = 5, nrow =5))
test[1] <- 1
pander(test, justify = "center")
Adding fig.align = "center" does not work and neither does justify = "center"
Does anyone know of a workaround ?
You could just add regular HTML tags to center the table (like <center>):
---
title: "test"
output:
html_document: default
pdf_document: default
---
<center>
```{r, fig.align="center"}
library(pander)
test <- as.data.frame(matrix(ncol = 5, nrow =5))
test[1] <- 1
pander(test, justify = "center")
```
</center>
If you want to show both the code and the centered table, but don't want the code centered, repeat the block, but don't evaluate it the first time, and then don't echo it the second time.
Here's an example:
Alternatively, add a custom CSS file with your styling options and add that to your header.
Example CSS (saved as "test.css"):
table {
margin:1em auto;
}
Example header:
---
title: "test"
output:
html_document:
css: test.css
---

How can I let a user control whether code is shown in a shiny rMarkdown document

I want to do something along the lines of
```{r, echo=FALSE, message=FALSE, error=FALSE, warning=FALSE}
radioButtons("code","Show code", choices=c("No","Yes"), inline = T)
if (input$code=="No") {
showCode <- FALSE
} else {
showCode <- TRUE
}
```
```{r,echo= showCode, message=FALSE, error=FALSE, warning=FALSE}
# Main Code
```
But not sure how to wrap the code reactively
Is this feasible?
TIA
We recently added code folding to R Markdown (the rmarkdown package >= v0.9.5): http://rmarkdown.rstudio.com/html_document_format.html#code_folding

Resources