【发布时间】:2015-09-10 03:29:07
【问题描述】:
我目前在 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"
【问题讨论】:
-
您可以使用
text <- paste("This means x value of", x, "was greater than 0")在输出中包含该值。这在您的非最小情况下不起作用吗? -
谢谢@DavidRobinson。我可能必须创造一个更好的 MWE!因为,我试图在文本中加入像 \Sexpr{} 和 \ref{} 这样的 LaTeX 语法。因此,我认为您的解决方案不适用于 \ref{}。
标签: r if-statement knitr sweave