【问题标题】:Best way to store and later use captions with Latex in Sweave?在 Sweave 中使用 Latex 存储和稍后使用字幕的最佳方式?
【发布时间】:2011-11-09 00:18:20
【问题描述】:

我想在 Sweave 的 R 模式下编写图形标题,然后将标题添加到列表中,然后在图形标题中使用它们,例如:

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]$"

但我收到以下错误:

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

有没有办法可以将这样的字符串存储在列表中,或者有更好的方法?

【问题讨论】:

    标签: r text latex sweave


    【解决方案1】:

    双重转义\ 字符。而且你不需要双方括号...

    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]$"
    

    坦率地说,我会写一个简单的辅助函数:

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

    你会得到:

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

    【讨论】:

    • 这回答了我的问题......我专注于一种方法来做到这一点,因为我已经写出了所有这些字符串,并想将它们包装在一个函数中......但是我找不到,除了将gsub() 包装在一个特定于任务的函数中。
    猜你喜欢
    • 1970-01-01
    • 2012-04-30
    • 1970-01-01
    • 1970-01-01
    • 2016-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    相关资源
    最近更新 更多