我目前正在使用R和RStudio中的knitr来生成LaTeX输出。我的代码是一个.Rnw文件(称为testKnitr.Rnw),它被编译为pdf文件:
knit("testKnitr.Rnw") // in RStudio
pdflatex testKnitr.tex // in terminal
我想在LaTeX中使用if-else语法,以便根据R变量的值输出两个LaTeX文本段落中的一个。在这些LaTeX段落中,我想使用\ Sexpr {}和\ ref。
之类的表达式我有一个最小工作示例,它基于对此处发布的类似问题的第二个答案:
How to write an if-then statement in LaTeX using the value of an R variable in knitr/Sweave
这是MWE:
\documentclass{article}
\begin{document}
<<include=FALSE>>=
library(knitr)
opts_chunk$set(
concordance=TRUE
)
@
<<condition, include=FALSE, echo=FALSE>>=
x<- rnorm(1)
if(x>0){
text <- "This means x value of \Sexpr{x} was greater than 0"
}else{
text <- "This means x value of \Sexpr{x} was less than 0"
}
@
Testing the code:
<<print, results='asis', echo=FALSE>>=
cat(text)
@
\end{document}
理想情况下,上述MWE的预期输出将是一个包含以下内容的报告:
"This means x value of 0.87 was greater than 0"
或
"This means x value of -0.87 was less than 0"