问题
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')`
回答1:
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
回答2:
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')`
来源:https://stackoverflow.com/questions/55233763/specifying-colour-in-html-and-pdf-output