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

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

问题描述

我正在扩展我在此发布的问题:



使用R变量作为条件的knitr / Sweave中的If-Else语句



I想在LaTeX中使用if-else语法,以便根据R变量(比如x)的值,输出两个LaTeX文本段落中的一个。如果x> 0,则LaTeX段落具有图形和表格。但是,如果x <0,则LaTeX段落只有一个数字(并且没有表格)。



我有一个MWE可行,并且基于已检查的答案上一篇文章:

  \documentclass [12pt,english,nohyper] {tufte-handout} 
\usepackage {tabularx}
\usepackage {longtable}

\ begin {document}

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

< ;< echo = FALSE,results ='asis'>> =
fname =myOutput.pdf
pdf(fname,width = 4,height = 4)
print( qplot(mpg,cyl,data = mtcars))
{dev.off(); invisible()}
cat(sprintf('\\begin {marginfigure}
\\\ \\includegraphics [width = 0.98 \\linewidth] {%s}
\\ caption {\\ label {mar:dataMtcars}关于mtcar数据集的评论。}
\\结束{marginfigure}',sub('\\。pdf','',fname)))
@

<< echo = FALSE,results ='asis'>> =
x< - rnorm(1)
if(x> 0 ){
myDF = data.frame(a = rnorm(1:5),b = rnorm(1:5),c = rnorm(1:5))
print(xtable(myDF,caption) ='数据框注释',label ='tab:myDataFrame'),floating = FALSE,tabular.environment =longtable,include.rownames = FALSE)
}
@

<< condition,echo = FALSE>> =
if(x> 0){
text< - Figure \\ref {mar:dataMtcars}显示mtcars数据组。 \\Sexpr {x}的x值大于0.表\\ref {tab:myDataFrame}显示我的数据框。
} else {
text< - Figure \\ref {mar:dataMtcars}显示了mtcars数据集。 \\Sexpr {x}的x值小于0.我们没有显示数据框。
}
@

测试代码:

<< print,results ='asis',echo = FALSE>> =
cat(text)
@

\ end {文件}

然后我将此MWE保存为类似testKnitr.Rnw,并运行:

  knit(input =testKnitr.Rnw,output =intermediate.Rnw)
knit2pdf(input =intermediate.Rnw ,output =doc_final.tex)

我想知道我是否有效地创建此代码,特别是因为我在之前的帖子中向我指出 - 在使用\Sexpr {}的情况下 - 有更简单的解决方案。在这里编织两次有点麻烦。



是否有更简单的方法来合并我的if / else语句来显示包含变量值,数字和/或表的两个段落之一,所有这些都基于变量的值?谢谢。


解决方案

类似于相关问题动态生成 \Sexpr {} 并且第二次解析中间输出不是在这种情况下是必要的。



问题的代码中发生了很多事情,但这是关键块(其中 x 获取在前一个块中分配的随机值):

 << condition,echo = FALSE>> = 
if(x> 0){
text< - Figure \\ref {mar:dataMtcars}显示mtcars数据集。\\Sexpr {x}的x值大于0.表\\\ \\ ref {tab:myDataFrame}显示我的数据框。
} else {
text< - Figure \\ref {mar:dataMtcars}显示mtcars数据集。\\Sexpr {x}的x值小于0。我们没有显示数据框。
}
@



直接替代 print ing \ Sexpr



\ Sexpr的直接替代品{} 粘贴 sprintf (我在 if branch和 else 分支中的一个用于演示):



<$ p $如果(x> 0){
text< - paste(Figure \\ref {mar:dataMtcars}显示mtcars数据集。,x,的x值大于0.表\\ref {tab:myDataFrame}显示我的数据框。)
} else {
text< - sprintf(Figure \\ref {mar:dataMtcars}显示mtcars数据集。%f的x值小于0.我们不显示数据框。,x )
}
@

当有条件地显示文本时这很有效不会太久。否则,如果 -statements,使用LaTeX 可能更方便。这样做的好处是,characer字符串/代码块中不会包含太多代码。然后, \Sexpr {} 可能再次有用。



使用LaTeX条件表达式



在LaTeX中编写条件表达式的方法很多,但最简单形式就足够了。




  • 首先,定义一个新的 if 我们称之为 ifPositive
    \ newif\ifPositive

  • 其次,使用R来插入 \Positivetrue
    \ Pososfalse 进入文件。

  • 第三,使用 \ifPositive ... \ ltse ... \ fi

      \ newif \ifPositive 

    << condtion2,echo = FALSE,results =asis>> =
    if(x> 0){
    cat(\\Positivetrue)
    } else {
    cat(\\Positivefalse)
    }
    @

    \ifPositive
    图\ref {mar:dataMtcars}显示mtcars数据集。 \ Sexpr {x}的x值大于0. Table \ref {tab:myDataFrame}显示我的数据框。
    \else
    图\ref {mar:dataMtcars}显示mtcars数据集。 \ Sexpr {x}的x值小于0.我们不显示数据框。
    \fi




其他备注



在问题中,有一个块生成 myOutput.pdf 。在那里,使用 pdf() dev.off()。这不是一个好的风格,杀死小猫。没有必要绕过 knitr 的生产图的机制;即使使用 marginfigure 等自定义环境而不是 figure 也是如此。块应替换为以下内容:

 << dataMtcars,echo = FALSE,fig.env =marginfigure ,out.width =0.98 \\ linewidth,fig.cap =关于mtcar数据集的评论。,fig.lp =mar:>> = 
print(qplot(mpg, cyl,data = mtcars))
@

fig.lp =mar:仅用于生成与问题 mar:dataMtcars 完全相同的标签。如果标签 fig:dataMtcars 也没问题,可以跳过它。



文件



最后,这里是完整的文件:

  \documentclass [12pt,english,nohyper] { tufte-handout} 
\usepackage {tabularx}
\usepackage {longtable}

\ begin {document}

<< setup,echo = FALSE>> =
library(knitr)
library(xtable)
library(ggplot2)
@

<< dataMtcars,echo = FALSE,fig.env =marginfigure,out.width =0.98 \\ linewidth,fig.cap =关于mtcar数据集的评论。,fig.lp =mar:>> ; =
print(qplot(mpg,cyl,data = mtcars))
@

<< echo = FALSE,results ='asis'>> =
x< - rnorm(1)
if(x> 0){
myDF< - data.frame(a = rnorm(1:5),b = rnorm(1: 5),c = rnorm(1:5))
print(xtable(myDF,caption ='Data frame comments',label ='tab:myDataFrame'),floating = FALSE,tabular.environment =longt ,include.rownames = FALSE
}
@

<<条件,echo = FALSE>> =
if(x> 0){
text< - paste(Figure \\ref {mar:dataMtcars}显示mtcars数据集。,x,的x值大于0.表\\ ref {tab:myDataFrame}显示我的数据框。)
} else {
text< - sprintf(Figure \\ref {mar:dataMtcars}显示mtcars数据集.x %f的值小于0.我们不显示数据框。,x)
}
@

测试代码:

<< print,results ='asis',echo = FALSE>> =
cat(text)
@

\ paragraph {Alternative:}

\ newif \ifPositive

<< condtion2,echo = FALSE,results =asis>> =
if(x> 0 ){
cat(\\Positivetrue)
} else {
cat(\\Positivefalse)
}
@

\ifPositive
图\ref {mar:dataMtcars}显示mtcars数据集。 \ Sexpr {x}的x值大于0. Table \ref {tab:myDataFrame}显示我的数据框。
\else
图\ref {mar:dataMtcars}显示mtcars数据集。 \ Sexpr {x}的x值小于0.我们不显示数据框。
\fi

\end {document}


I am extending a question I posted here:

If-Else Statement in knitr/Sweave using R variable as conditional

I would like to use an if-else syntax in LaTeX so that, depending on the value of an R variable (say x), one of two LaTeX text paragraphs are output. If x>0, then the LaTeX paragraph has a figure and a table. However, if x<0, then the LaTeX paragraph has just a figure (and no table).

I have a MWE that works and is based on the checked answer at the previous post:

\documentclass[12pt,english,nohyper]{tufte-handout}
\usepackage{tabularx}
\usepackage{longtable}

\begin{document}

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

<<echo=FALSE,results='asis'>>=
fname="myOutput.pdf"
pdf(fname,width=4,height=4)
print(qplot(mpg,cyl,data=mtcars))
{dev.off();invisible()}
cat(sprintf('\\begin{marginfigure}
\\includegraphics[width=0.98\\linewidth]{%s}
\\caption{\\label{mar:dataMtcars}Comments about mtcar dataset.}
\\end{marginfigure}',sub('\\.pdf','',fname)))
@

<<echo=FALSE,results='asis'>>=
x<- rnorm(1)
if (x>0){
  myDF = data.frame(a=rnorm(1:5),b=rnorm(1:5),c=rnorm(1:5))
  print(xtable(myDF,caption='Data frame comments', label='tab:myDataFrame'),floating=FALSE, tabular.environment = "longtable",include.rownames=FALSE)
}
@

<<condition, echo=FALSE>>=
if(x>0){
  text <- "Figure \\ref{mar:dataMtcars} shows the mtcars data set. The x value of \\Sexpr{x} was greater than 0. Table \\ref{tab:myDataFrame} shows my data frame."
  }else{
  text <- "Figure \\ref{mar:dataMtcars} shows the mtcars data set. The x value of \\Sexpr{x} was less than 0. We do not show a data frame."
  }
@

Testing the code: 

<<print, results='asis', echo=FALSE>>=
cat(text)
@

\end{document}

I then save this MWE as something like testKnitr.Rnw, and run:

knit(input = "testKnitr.Rnw", output = "intermediate.Rnw")
knit2pdf(input = "intermediate.Rnw", output = "doc_final.tex")

I am wondering if I am creating this code efficiently, especially because it was pointed out to me in my previous post that - in the case of just using \Sexpr{} - there were easier solutions. It is a bit cumbersome to knit twice here.

Is there an easier way to incorporate my if/else statement to display one of two paragraphs containing the variable value, figures, and/or tables, all based on the value of the variable? Thank you.

解决方案

Similar to the related question that has been linked above dynamically generating \Sexpr{} and parsing the intermediate output a second time is not necessary in this scenario.

Many things happen in the code from the question, but this is the key chunk (where x gets a random value assigned in a previous chunk):

<<condition, echo=FALSE>>=
if (x > 0) {
  text <- "Figure \\ref{mar:dataMtcars} shows the mtcars data set. The x value of \\Sexpr{x} was greater than 0. Table \\ref{tab:myDataFrame} shows my data frame."
  } else {
    text <- "Figure \\ref{mar:dataMtcars} shows the mtcars data set. The x value of \\Sexpr{x} was less than 0. We do not show a data frame."
    }
@

Direct substitutes for printing \Sexpr

Straighforward alternatives to \Sexpr{} are paste and sprintf (I use one in the if branch and one in the else branch just for demonstration):

<<condition, echo=FALSE>>=
if (x > 0) {
  text <- paste("Figure \\ref{mar:dataMtcars} shows the mtcars data set. The x value of", x, "was greater than 0. Table \\ref{tab:myDataFrame} shows my data frame.")
  } else {
    text <- sprintf("Figure \\ref{mar:dataMtcars} shows the mtcars data set. The x value of %f was less than 0. We do not show a data frame.", x)
    }
@

This works well when the text to be conditionally displayed is not too long. Otherwise, it might be more convenient to use LaTeX if-statements. This has the advantage that not too much code is wrapped in characer strings / code chunks. Then, \Sexpr{} might again be useful.

Using LaTeX conditional expressions

There are many ways to write conditional expressions in LaTeX, but the most simple form will be enough.

  • First, define a new if that we'll call ifPositive: \newif\ifPositive.
  • Second, use R to insert \Positivetrue or \Positivefalse into the document.
  • Third, use \ifPositive … \else … \fi.

    \newif\ifPositive
    
    <<condtion2, echo = FALSE, results = "asis">>=
    if (x > 0) {
      cat("\\Positivetrue")
    } else {
      cat("\\Positivefalse")
    }
    @
    
    \ifPositive
    Figure \ref{mar:dataMtcars} shows the mtcars data set. The x value of \Sexpr{x} was greater than 0. Table \ref{tab:myDataFrame} shows my data frame.
    \else
    Figure \ref{mar:dataMtcars} shows the mtcars data set. The x value of \Sexpr{x} was less than 0. We do not show a data frame.
    \fi
    

Other remarks

In the question there is a chunk that generates myOutput.pdf. There, pdf() and dev.off() are used. This is no good style and kills kittens. There is no need to bypass knitr's mechanisms for producing plots; not even when custom environments like marginfigure instead of figure are to be used. The chunk should be replaced by something like this:

<<dataMtcars, echo=FALSE, fig.env = "marginfigure", out.width = "0.98\\linewidth", fig.cap = "Comments about mtcar dataset.", fig.lp = "mar:">>=
print(qplot(mpg,cyl,data=mtcars))
@

fig.lp = "mar:" is only necessary in order to produce the exactly same label as in the question mar:dataMtcars. It could be skipped if the label fig:dataMtcars was also okay.

Document

Finally, here the complete document:

\documentclass[12pt,english,nohyper]{tufte-handout}
\usepackage{tabularx}
\usepackage{longtable}

\begin{document}

<<setup, echo = FALSE>>=
library(knitr)
library(xtable)
library(ggplot2)
@

<<dataMtcars, echo=FALSE, fig.env = "marginfigure", out.width = "0.98\\linewidth", fig.cap = "Comments about mtcar dataset.", fig.lp = "mar:">>=
print(qplot(mpg,cyl,data=mtcars))
@

<<echo=FALSE,results='asis'>>=
x <- rnorm(1)
if (x > 0) {
  myDF <- data.frame(a = rnorm(1:5), b = rnorm(1:5), c = rnorm(1:5))
  print(xtable(myDF, caption= 'Data frame comments', label='tab:myDataFrame'), floating = FALSE, tabular.environment = "longtable", include.rownames=FALSE)
}
@

<<condition, echo=FALSE>>=
if (x > 0) {
  text <- paste("Figure \\ref{mar:dataMtcars} shows the mtcars data set. The x value of", x, "was greater than 0. Table \\ref{tab:myDataFrame} shows my data frame.")
  } else {
    text <- sprintf("Figure \\ref{mar:dataMtcars} shows the mtcars data set. The x value of %f was less than 0. We do not show a data frame.", x)
    }
@

  Testing the code:

<<print, results='asis', echo=FALSE>>=
  cat(text)
@

\paragraph{Alternative:}

\newif\ifPositive

<<condtion2, echo = FALSE, results = "asis">>=
if (x > 0) {
  cat("\\Positivetrue")
} else {
  cat("\\Positivefalse")
}
@

\ifPositive
Figure \ref{mar:dataMtcars} shows the mtcars data set. The x value of \Sexpr{x} was greater than 0. Table \ref{tab:myDataFrame} shows my data frame.
\else
Figure \ref{mar:dataMtcars} shows the mtcars data set. The x value of \Sexpr{x} was less than 0. We do not show a data frame.
\fi

\end{document}

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

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