1
votes

I'd like to produce a LaTeX table in R using either stargazer or xtable. One of the columns in the table will include LaTeX code for referring to figures elsewhere in my document. These figures are labelled using the convention \label{Figure: i} (where i is an integer).

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. Does anyone know how I can get around this please?

Thanks

1

1 Answers

1
votes

I don't know about stargazer(), but print.xtable() has a sanitize.text.function option that will be useful to accomplish this task. From help("print.xtable"):

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. Default value is 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. 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).