An answer by Nicholas Hamilton指定如何使用R表达式在Markdown的PDF和HTML输出中使用彩色文本。
如果我创建一个RMarkdown文档,我不会感到高兴,警告消息是
colFmt(“ MY RED TEXT”,“ red”)中的错误:找不到对象'opts_knit' 调用:... inline_exec-> hook_eval-> withVisible-> eval-> eval-> colFmt 执行停止
我想念什么?
复制并粘贴以下RMarkdown:
---
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')`
答案 0 :(得分:1)
将opts_knit$get
更改为knitr::opts_knit$get
,您的代码应该可以使用。
请参见https://stat.ethz.ch/R-manual/R-devel/library/base/html/ns-dblcolon.html
答案 1 :(得分:0)
这是一个rmarkdown代码的示例,该代码自包含且有效,并使用十六进制颜色ID在pdf和html中提供一致的颜色。感谢Kenji的贡献指出我需要knitr库。
---
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')`