【问题标题】:Sanitize column names for Bold and Identity with xtable in knitr在 knitr 中使用 xtable 清理粗体和标识的列名
【发布时间】:2017-10-31 16:43:13
【问题描述】:

有没有办法传递 xtable 的标识函数来清理列名和另一个自定义函数来加粗列名?下面有两个代码块,一个用于设置虚拟函数,另一个用于打印 xtable。它在第一列名称中的 $ 符号上失败,并且表值中的 $ 符号已正确清理。

谢谢!

<<setup>>=
library(knitr)
library(xtable)
two_functions = function(x){
  paste("\\textbf{", x, "}", sep = "")
  # use xtable's 'identity' function to convert special characters
}

options(xtable.sanitize.colnames.function = two_functions)
@

<<xtable, results='asis'>>=
xtab = data.frame(a = c("Horse and $buddy", "Paddy Wagon", "Hospital Care", "Peanut butter and toast", "Cheese Whiz with Mayo"),
                  b = c(10000000, 200000.4533, 3098765435.65456, 408765467.654456, 50.00000))
colnames(xtab) = c("Hello money $ bag$", "Numbers")
print(xtable(xtab))
@

【问题讨论】:

  • 您能否提供有关您遇到的错误的更多信息?您如何通过 RStudio 中的按钮编织文档?显式从控制台?当我运行代码时,我没有遇到任何错误,结果符合预期。
  • @Peter 该代码没有提供错误,但列标题中的 $ 符号没有显示给我。它将 Latex 表列标题置于数学模式。我想要一个函数来在列标题上运行默认的“身份”清理功能,并使列标题加粗。希望澄清...?
  • @Peter 为了回答前面的问题(抱歉)我正在使用 RStudio 上的编译按钮使用 knitr、pdflatex 进行编织

标签: r knitr xtable


【解决方案1】:

我认为解决方案可能就像在 two_functions 调用中使用 gsub 一样简单。

\documentclass{article}
\begin{document}
<<<setup>>=
library(knitr)
library(xtable)

two_functions = function(x){
    gsub("\\$", "\\\\$", paste("\\textbf{", x, "}", sep = ""))
}

options(xtable.sanitize.colnames.function = two_functions,
        xtable.sanitize.rownames.function = NULL,
        xtable.sanitize.text.function     = NULL)

@

<<xtable, results='asis'>>=
xtab = data.frame(a = c("Horse and $buddy", "Paddy Wagon", "Hospital Care", "Peanut butter and toast", "Cheese Whiz with Mayo"),
                  b = c(10000000, 200000.4533, 3098765435.65456, 408765467.654456, 50.00000))
colnames(xtab) = c("Hello money $ bag$", "Numbers")
print(xtable(xtab))
@
\end{document}

编辑

要使用默认的 xtable 函数来清理字符串,请将上面的 two_functions 函数替换为以下内容:

two_functions = function(x){
  paste0("\\textbf{", xtable::sanitize(x, type = "latex"), "}")
}

这里首先调用xtable::sanitize 函数,然后将生成的字符串放入LaTeX \textbf{} 环境中。

结果表是:

【讨论】:

  • @彼得尼斯头像顺便说一句。是的,我同意这是替换 $ 符号的有效功能,但默认清理功能涵盖的符号不仅仅是 $ 字符。因此,理想的函数将结合 sanitize(不仅包括 $ 字符)函数和粗体函数。
  • @Prevost,我已经编辑了我的答案。在two_functions 调用中使用xtable::sanatize 应该可以解决问题。
  • 我想就是这样!当我回到我的电脑时,我会尝试一下,然后如果它对我有用,我会标记你的答案是正确的。再次感谢....
猜你喜欢
  • 1970-01-01
  • 2018-06-29
  • 2015-08-12
  • 2013-12-04
  • 1970-01-01
  • 2015-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多