Search code examples
rtextlatexsweave

Best way to store and later use captions with Latex in Sweave?


I would like to write figure captions in the R mode of Sweave and then, add the captions to a list, and later use them in a figure caption, for example:

caption <- list()
myresult <- data.frame(name = c('fee', 'fi'), x = c(1,2))
caption[['fig1']] <- "$\text{\Sexpr{myresult$name[1]}}\Sexpr{myresult$x[1]$" 
caption[['fig2']] <- "$\text{\Sexpr{myresult$name[2]}}\Sexpr{myresult$x[2]$"

But I get the following error:

Error: '\S' is an unrecognized escape in character string starting "$\text{\S"

Is there a way that I can store such a string in a list, or a better approach?


Solution

  • Double-escape \ characters. And you don't need double square brackets...

    caption <- list()
    myresult <- data.frame(name = c('fee', 'fi'), x = c(1,2))
    caption['fig1'] <- "$\\text{\\Sexpr{myresult$name[1]}}\\Sexpr{myresult$x[1]$" 
    caption['fig2'] <- "$\\text{\\Sexpr{myresult$name[2]}}\\Sexpr{myresult$x[2]$"
    

    Frankly, I'd write a simple helper function:

    genCaption <- function(name, value){
        sprintf("$\\text{%s}%.3f$", name, value)
    }
    

    and you'll get:

    > genCaption("pi", pi)
    [1] "$\text{pi}3.142$"