0

Is there a way to use an if-else statement in an sweave document, so that a figure is only shown depending on the value of an R object. I tried different approaches (two of them are below), but I did not find a solution that is working.

Alternative 1:

R-Code:

x <- seq(0, 10, length.out=11)
y <- seq(0, 10, length.out=11)
show_figure <- sample(c(TRUE, FALSE), 1)

Latex-Code:

...
<<fig = show_figure, echo = FALSE>>=
plot(x,y)
@
...

Alternative 2:

R-Code:

...
figure <- if(show_figure) {
             "<<fig = TRUE, echo = FALSE>>=
             plot(x,y)
             @"
          } else {}

Latex-Code:

...
\Sexpr{figure}
...

bumped to the homepage by Community yesterday

This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.

1

You cannot use a LaTeX conditionals for this. LaTeX simply do not know nothing about the R code and simply typeset the output of R. But you can use a R conditional:

\documentclass{article}
\begin{document}
<<echo=F,results='asis'>>=
    x <- seq(0, 10, length.out=11)
    y <- seq(0, 10, length.out=11)
    show <- sample(c(TRUE, FALSE), 1)
    if(show==TRUE){plot(x,y)} else{cat("No plot,sorry")}
@
\end{document}

This produces randomly a PDF with a scatterplot or only the warning "No plot, sorry".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.