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:


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=""));


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], ")");

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.


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

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

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

a <- sayhi()

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

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


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.

  • thanks for the pointer I have included more details to the question.
    – klonq
    Jul 8 '11 at 12:11

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.