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 runcat
on the value returned from evaluating what's inside the\Sexpr
; sincecat
doesn't return a value,\Sexpr
doesn't have anything to output.See the following
.Rnw
file for examples.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.