[Tex/LaTex] Difference between \Sexpr and <<>>=

rsweave

I am new to sweave and learning a lot. For the most part \Sexpr works well for simple variables and also calling R functions.

But other times it will fail, I have found that I can get around this using the <<>>= command. I am interested to know what the difference is, and when I should use which one.

For instance:

I can use \Sexpr{parc.name(parc)} but \Sexpr{p_curve.data.points(p_curve.data);} will not work, however the following will work:

<<echo=false,results=tex>>=
            p_curve.data.points(p_curve.data);
@

Where the functions are defined in a seperate file using source("filename.R")

parc.name <- function(code) {
    conn <- connect();
    res <- dbGetQuery(conn, paste("SELECT displayname FROM machinepark WHERE name='", code, "' LIMIT 1", sep=""));
    disconnect(conn);
    res$displayname[1];
}

and

p_curve.data.points <- function(pc_data) {
    rows <- length(pc_data$power);
    for(i in 1:rows){
        cat("(", pc_data$windspeed[i], ",", pc_data$power[i], ")");
    }
}

Best Answer

cat is not appropriate in \Sexpr statements. I believe it tries to run cat on the value returned from evaluating what's inside the \Sexpr; since cat doesn't return a value, \Sexpr doesn't have anything to output.

See the following .Rnw file for examples.

\documentclass{article}
\begin{document}

<<>>=
sayhi <- function(k=2) {for(i in 1:k) cat("hi",i,"| ") }
sayhi()
@ 

But with Sexpr, {\tt sayhi()} prints <\Sexpr{sayhi()}>.

Note that {\tt sayhi()} returns nothing; that's why Sexpr doesn't work.

<<>>=
a <- sayhi()
cat(a)
@ 

<<>>=
savehi <- function(k=2) {
  out <- c()
  for(i in 1:k) {
    out <- paste(out, "hi", i,"| ")
  }
  out
}
hi <- savehi()
cat(hi)
@ 

And with Sexpr, {\tt savehi()} prints <\Sexpr{savehi()}>.

\end{document}

Aside from original answer: Another "gotcha" with \Sexpr expressions is trying to use curly brackets. Curly brackets are not allowed in \Sexpr expressions. Instead do the computation in a hidden code chunk and use the result in an \Sexpr.

See the Sweave manual for details.

Also see this question at stackoverflow.