Specifying colour in HTML and PDF output - html

An answer by Nicholas Hamilton specifies how to use colour text in PDF and HTML output from Markdown using an R expression.
If I create an RMarkdown document, I get no joy, Warning message is
Error in colFmt("MY RED TEXT", "red") : object 'opts_knit' not found
Calls: ... inline_exec -> hook_eval -> withVisible -> eval -> eval -> colFmt
Execution halted
What am I missing?
Copy and paste of RMarkdown below:
---
title: "test colour"
author: "mbn"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document.
```{r cars}
colFmt = function(x,color){
outputFormat = opts_knit$get("rmarkdown.pandoc.to")
if(outputFormat == 'latex')
paste("\\textcolor{",color,"}{",x,"}",sep="")
else if(outputFormat == 'html')
paste("<font color='",color,"'>",x,"</font>",sep="")
else
x
}
```
## Test colour now
`r colFmt("MY RED TEXT",'red')`

Change opts_knit$get to knitr::opts_knit$get and your code should work.
See https://stat.ethz.ch/R-manual/R-devel/library/base/html/ns-dblcolon.html

Here is an example of an rmarkdown code that is self contained and works, and uses hex colour ids to give consistent colours across pdf and html. Thanks to contributions from Kenji for pointing out I needed knitr library.
---
title: "test colour"
author: "mbn"
output: html_document
#output: pdf_document
header-includes:
\usepackage[usenames,dvipsnames]{xcolor}
---
```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document.
```{r cars}
colFmt = function(x,color){
outputFormat = opts_knit$get("rmarkdown.pandoc.to")
if(outputFormat == 'latex')
paste("\\textcolor[HTML]{",color,"}{",x,"}",sep="")
else if(outputFormat == 'html')
paste("<font color='",color,"'>",x,"</font>",sep="")
else
x
}
```
## Test colour now
`r colFmt("My colored text favorite green latex/pdf and html",'7ac143')`

Related

Add an equation using roxygen2 in Rscript

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?

Evaluate html script stored in R object in R-markdown

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

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

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 ---**

knitr Markdown LateX like table within HTML document

I would like to produce "LaTeX-like" table within an HTM document using knitr markdown (.Rmd) through:
knitr::knit2html(input="D:/...Rmd", output="D:/...report.html")
Here is an example. However, if I decided to produce a report, the LaTeX table would be incorrect:
library(xtable)
xtabl <- xtable(head(CO2))
print(xtabl, type="latex", include.rownames=FALSE)
The above gives:
As suggested here is the result. It was NOT a "LaTeX-like" table!
xtabl <- xtable(head(CO2))
print.xtable(xtabl, type="html", include.rownames=FALSE)
EDIT:
What I mean by "LaTeX-like" table is this:
The R Markdown cheat sheet provides a visual comparison of libraries kable, xtable and stargazer. Stargazer could be what you are looking for.
Also have a look into the htmlTable package.
Further customizations could be made with a custom CSS file.
Here's an example of a basic table with htmlTable:
---
title: "Untitled"
author: "Author"
date: "2/5/2017"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r}
library(htmlTable)
```
```{r, results="asis"}
tab = cbind.data.frame(
sapply(iris[1:5 , sapply(iris, is.numeric)], function(x) sprintf("%1.1f", x)),
Species=iris$Species[1:5]
)
htmlTable(tab, rnames=FALSE, align="rrrrr", align.header="rrrrr",
css.cell = c(rep("padding-left: 5em", 4), "padding-left: 2em"))
```
I have used knitr::kable for producing the desired tables.
mydata <- data.frame(SrNo=c(1,2,3,4), websites=c("stackoverflow", "twitter", "facebook", "google"))
knitr::kable(mydata)
kable function accepts a format argument with possible values latex, html, etc. see the documentation for details
Complete Markdown file
---
title: "kable"
author: "Imran Ali"
date: "February 6, 2017"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r, echo=FALSE}
mydata <- data.frame(SrNo=c(1,2,3,4), websites=c("stackoverflow", "twitter", "facebook", "google"))
knitr::kable(mydata)
```