I want to use a text variable for a html, pdf, and word output with knitr. This is the code I currently have in markdown
I want to set a variable
var <- "just some text"
so that I don't need to write the text 3 different times
(please apologize the bad code, I am very new to this)
For HTML Only ```{asis, echo=is_html_output()} <p>just some text</p> ``` For PDF Only \\color{ecbblue}{\\scriptsize{just some text}} For DOCX Only ```{asis, echo=is_word_output()} just some text
If you want to work in LaTex you can use this code :
\usepackage{xspace}
newcommand{\VarName}{text to insert\xspace}
Then whenever you want
text to insert
So as an example you could do :
\color{blue}{\scriptsize{\VarName}}
would return text to insert in blue just like you want. This will indeed only work for text variable.
Edit : while the other answer is good, if you want to do it the R way I suggest to instead use the pander
package which does a really good job and is even simpler.
install.packages("pander")
library("pander")
For LaTeX(PDF) in your R chunks simply do :
pander(cat("\\textcolor{red}{", var ,"}"))
For HTML in your R chunks simply do :
pander(cat("<span style=color:red>", var, "</span>"))
You can define your variable in an invisible code chunk and output it in an inline expression. That way you don't need to handle <p>
etc.:
---
output:
pdf_document: default
word_document: default
html_document: default
---
```{r, include=FALSE}
var <- "just some text"
h2 <- "Text2"
```
## `r h2`
`r if(knitr::is_latex_output()) paste("\\textcolor{blue}{\\scriptsize", var, "}") else var`
Note that I am using \\textcolor
instead of \\color
, since the latter does not take an argument and will make all following text also blue.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.