How to write an if-then statement in LaTeX using the value of an R variable in knitr/Sweave

陌路散爱 提交于 2019-12-03 08:13:52

Add \usepackage{comment} to the preamble of your latex file.

At the line before the optional section starts, do

<<startcomment, results='asis', echo=FALSE>>=
if(!CreateOptionalSection){
  cat("\\begin{comment}")
}
@

At the line after the optional section ends, do

<<endcomment, results='asis', echo=FALSE>>=
if(!CreateOptionalSection){
  cat("\\end{comment}")
}
@

You can do it directly in R code in your .Rnw file, using cat to paste the section. Here is an example, when x > 0 it creates section 1, when x < 0 it creates 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}

This will give you:

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!