Knitr / Sweave中的If-Else语句使用R变量作为条件 [英] If-Else Statement in knitr/Sweave using R variable as conditional

查看:237
本文介绍了Knitr / Sweave中的If-Else语句使用R变量作为条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用R和RStudio中的knitr来生成LaTeX输出。我的代码是.Rnw文件(称为testKnitr.Rnw),编译为pdf文件,其中包含:

I am currently using knitr in R and RStudio to produce a LaTeX output. My code is a .Rnw file (called, say, testKnitr.Rnw) that is compiled to a pdf file with:

knit("testKnitr.Rnw") // in RStudio
pdflatex testKnitr.tex // in terminal

我想在LaTeX中使用if-else语法,以便根据R变量的值输出两个LaTeX文本段落中的一个。在这些LaTeX段落中,我想使用像\Sexpr {}和\ ref这样的表达式。

I would like to use an if-else syntax in LaTeX so that, depending on the value of an R variable, one of two LaTeX text paragraphs are output. In these LaTeX paragraphs, I would like to use expressions like \Sexpr{} and and \ref.

我有一个基于的最小工作示例这里发布了类似问题的第二个答案:

I have a minimal-working-example that is based on the second answer to a similar question posted here:

如何使用knitr / Sweave中R变量的值在LaTeX中编写if-then语句

这是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的预期输出将一行包含以下内容的报告:

Ideally, the intended output of the above MWE would a report with one line that contained something like:

"This means x value of 0.87 was greater than 0"

"This means x value of -0.87 was less than 0"


推荐答案

<在回答这个问题之前,我想看看这个是否应该完成的元问题。

我不这么认为。我们在这里基本上做的是使用 knitr 在文档中插入 \Sexpr {x} 然后解释 \Sexpr {X} 。没有(显而易见的)原因我们应该绕道而不是直接将 x 的值插入到文档中。

I don't think so. What we are basically doing here is using knitr to insert \Sexpr{x} in a document and then interpret \Sexpr{x}. There are no (obvious) reasons why we should take this detour instead of inserting the value of x directly to the document.

以下最小例子说明了如何做到这一点:

The following minimal example shows how it could be done anyways:

\documentclass{article}

\begin{document}

<<setup, echo = FALSE>>=
library(knitr)
knit_patterns$set(header.begin = NULL)
@

<<condition, 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}

这里有两件事很重要:


  • 我们需要转义 \Sexpr 中的反斜杠,产生 \Sexpr

  • 我们需要设置 knit_patterns $ set(header.begin = NULL)

  • We need to escape the backslash in \Sexpr, resulting in \Sexpr.
  • We need to set knit_patterns$set(header.begin = NULL).

编译文档:


  • 将其另存为 doc.Rnw

  • 然后执行:

  • Save it as doc.Rnw.
  • Then execute:

knitEnv <- new.env()
knit(input = "doc.Rnw", output = "intermediate.Rnw", envir = knitEnv)
knit2pdf(input = "intermediate.Rnw", output = "doc_final.tex", envir = knitEnv)


knit 的第一次调用会生成 intermediate.Rnw ,其中包含以下内容:

The first call of knit generates intermediate.Rnw with the following content:

\documentclass{article}

\begin{document}

Testing the code:

This means x value of \Sexpr{x} was less than 0

\end{document}

你应该注意编织r 没有像LaTeX代码那样包含任何定义,命令等。这是因为设置 header.begin = NULL 并记录了这里。我们需要这种行为,因为我们想要在第二步中再次编织生成的文档 ,并且当两次定义相同的东西时,LaTeX不喜欢它。

You should note that knitr didn't include any definitions, commands etc. as usual to the LaTeX code. This is due to setting header.begin = NULL and documented here. We need this behavior because we want to knit the resulting document again in the second step and LaTeX doesn't like it when the same stuff is defined twice.

创建新环境 knitEnv 并将其设置为 envir 是可选的。如果我们跳过这个,变量 x 将在全局环境中创建。

Creating the new environment knitEnv and setting it as envir is optional. If we skip this, the variable x will be created in the global environment.

在第二步中我们使用 knit2pdf 编织 intermediate.Rnw 并在之后立即生成PDF。如果在第一步中使用了 envir ,我们也需要在这里使用它。这是 x 的方式,它的值从第一个编织步骤传送到第二个编织步骤。

In the second step we use knit2pdf to knit intermediate.Rnw and immediately generate a PDF afterwards. If envir was used in the first step, we need to use it here too. This is how x and it's value are conveyed from the first to the second knitting step.

这次所有的包括gory LaTeX的东西,我们得到 doc_final.tex

This time all the gory LaTeX stuff is included and we get doc_final.tex with:

\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
  \ifdim\Gin@nat@width>\linewidth
    \linewidth
  \else
    \Gin@nat@width
  \fi
}
\makeatother

%% more gory stuff %%


\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}

Testing the code:

This means x value of \ensuremath{-0.294859} was less than 0

\end{document}

这篇关于Knitr / Sweave中的If-Else语句使用R变量作为条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆