TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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], ")");
share|improve this question
up vote 4 down vote accepted

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.

share|improve this answer
thanks for the pointer I have included more details to the question. – klonq Jul 8 '11 at 12:11

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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