我目前正在使用knitr以及R 3.0.2和RStudio来生成LaTeX报告。我的报告输入为.Rnw文件,并使用knit2pdf函数进行编译。
我想使用if-then formulation in LaTeX来创建一个单独的部分,但if-then条件使用R中变量的值(让我们称之为CreateOptionalSection
)。
这可能吗?如果是这样,我如何在.tex文档中引用R变量?
答案 0 :(得分:5)
将\usepackage{comment}
添加到您的乳胶文件的前导码中。
在可选部分开始前的行,执行
<<startcomment, results='asis', echo=FALSE>>=
if(!CreateOptionalSection){
cat("\\begin{comment}")
}
@
在可选部分结束后的行处,执行
<<endcomment, results='asis', echo=FALSE>>=
if(!CreateOptionalSection){
cat("\\end{comment}")
}
@
答案 1 :(得分:2)
您可以直接在R
文件的.Rnw
代码中使用cat
粘贴该部分。以下是一个示例,当x > 0
创建section 1
时,x < 0
创建时section 2
:
\documentclass{article}
\begin{document}
<<condition, include=FALSE, echo=FALSE>>=
x<- rnorm(1)
if(x>0){
text <- "\\section{Section 1}
This is new section 1"
}else{
text <- "\\section{Section 2}
This is new section 2"
}
@
Testing the code: the result of x (which here was \Sexpr{x}) will determine the section.
<<print, results='asis', echo=FALSE>>=
cat(text)
@
\end{document}
这会给你: