简体   繁体   English

如何将 LaTeX 代码包含到 Stargazer 和 xtable 输出中?

[英]How to include LaTeX code into Stargazer and xtable output?

I'd like to produce a LaTeX table in R using either stargazer or xtable.我想使用 stargazer 或 xtable 在 R 中生成一个 LaTeX 表。 One of the columns in the table will include LaTeX code for referring to figures elsewhere in my document.表中的一列将包含 LaTeX 代码,用于引用我文档中其他地方的数字。 These figures are labelled using the convention \\label{Figure: i} (where i is an integer).这些数字使用约定 \\label{Figure: i} (其中 i 是整数)进行标记。

I'm trying something along these lines:我正在尝试以下方法:

df <- data.frame(
          Name = c("My First Graph", "My Second Graph"),
          Figure = paste0("\\ref{Fig: ",1:2))
          )
stargazer(df,summary=FALSE)

However, the output automatically escapes the backslashes and the curly braces in the final LaTeX output.但是,输出会自动转义最终 LaTeX 输出中的反斜杠和花括号。 Does anyone know how I can get around this please?有谁知道我该如何解决这个问题?

Thanks谢谢

I don't know about stargazer() , but print.xtable() has a sanitize.text.function option that will be useful to accomplish this task.我不知道stargazer() ,但print.xtable()有一个sanitize.text.function选项,这将有助于完成此任务。 From help("print.xtable") :来自help("print.xtable")

sanitize.text.function sanitize.text.function

All non-numeric entries (except row and column names) are sanitized in an attempt to remove characters which have special meaning for the output format.所有非数字条目(行和列名称除外)都经过清理,以尝试删除对输出格式具有特殊含义的字符。 If sanitize.text.function is not NULL, it should be a function taking a character vector and returning one, and will be used for the sanitization instead of the default internal function.如果 sanitize.text.function 不为 NULL,则它应该是一个接受字符向量并返回一个的函数,并将用于清理而不是默认的内部函数。 Default value is NULL.默认值为 NULL。

So, we can do the following:因此,我们可以执行以下操作:

df <- data.frame(
    Name = c("My First Graph", "My Second Graph"),
    Figure = paste0("\\ref{Fig: ", 1:2, "}")
)
tbl <- xtable(df)
print(tbl, include.rownames = FALSE, sanitize.text.function = function(x) x)

which gives the output I believe you want:这给出了我相信你想要的输出:

% latex table generated in R 3.4.4 by xtable 1.8-2 package
% Mon Jul 15 10:30:31 2019
\begin{table}[ht]
\centering
\begin{tabular}{ll}
  \hline
Name & Figure \\ 
  \hline
My First Graph & \ref{Fig: 1} \\ 
  My Second Graph & \ref{Fig: 2} \\ 
   \hline
\end{tabular}
\end{table}

Warning警告

This overrides print.xtable() 's default text sanitation, so only do it if you don't need anything cleaned.这会覆盖print.xtable()的默认文本卫生,所以只有在不需要清理任何东西时才这样做。 If you are in a more complicated situation, like you want some things cleaned and not others, you'll need to tweak this solution (probably quite a bit).如果您处于更复杂的情况,例如您想要清理某些东西而不是其他东西,则需要调整此解决方案(可能相当多)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM