Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do you loop over a global variable in Sweave

Tags:

r

sweave

I have a big Sweave file with a variable called "specialty" near the top. The rest of this file is Latex and R, and uses this variable.

How can I loop over various values for "specialty"?

Two possibilities are:

  1. Make the file be one big loop (and convert the Latex parts to R).
  2. Write a script that copies the Sweave file, replace the value of "specialty", and run Sweave on each copy.

Can you comment on these ideas, or suggest better ones?

like image 373
Winston C. Yang Avatar asked Dec 12 '22 22:12

Winston C. Yang


1 Answers

Here is some information that may be helpful to people who are new to brew.

(I learned about brew today and used it to create a book document, with a chapter for each "specialty".)

Shane's link is helpful. Another link is Brew. This has downloads and a short reference manual (seven pages).

In at least one way, brew is nicer than Sweave:

  • In brew, the tags are simpler, being variations of <%...%>.
  • In Sweave, the tags are <<...>>=...@ and \Sexpr{...}.

If you want to try brew, do the following in R:

install.packages("brew")
library(brew)

Save the following brew code in a file called book.brew. The code prints some digits of pi, with one digit per chapter. Note that there is one loop, and that parts of it are in Latex, and parts of it are in brew tags.

   \documentclass{book}
    \title{A book}
    \begin{document}
    \maketitle
    <%# This comment will not appear in the Latex file. %>
    <%
    digits = c(3, 1, 4, 1, 5, 9)
    for (i in 1:length(digits))
    {
    %>
    \chapter{Digit $<%= i %>$}
    Digit $<%= i %>$ of $\pi$ is $<%= digits[i] %>$.
    <%
    }
    %>
    \end{document}

Note: when you save the file, make the last line be a blank line, or brew will give you a warning about an unfinished line.

In R, type

brew("/your/path/to/book.brew", "/where/you/want/brew/to/create/book.tex")

Compile the Latex file book.tex.

like image 87
Winston C. Yang Avatar answered Jan 08 '23 10:01

Winston C. Yang