如何使用 xtable 在 table 或数据框的列名中设置空格

How to set spaces in the column names of a table or data frame using xtable

所以我想在数据框列的名称中的单词之间使用空格,并将数据框打印为 latex 格式的 pdf。但是,当我使用 xtable() 执行此操作时,列的名称会合并。

例如,我希望第二列的标题看起来像 "Categoria de Referencia"。相反,我得到的是:

有人知道如何解决这个问题吗?这是将数据帧转换为乳胶的 R 块:

tab<-xtable(dat,caption="Efectos de las Variables sobre la Probabilidad de Conversión",digits=2)
print(tab,latex.environments = "center",include.rownames=FALSE)

这是生成数据框的代码:

structure(list(Variable = structure(c(4L, 3L, 3L, 3L, 3L, 3L, 
2L, 1L), .Label = c("App", "Clicker", "País", "Uso"), class = "factor"), 
    Categoría.de.Referencia = structure(c(3L, 1L, 1L, 1L, 1L, 
    1L, 2L, 4L), .Label = c("Brasil", "Clicker", "No Acaba Unidad", 
    "No Usa App"), class = "factor"), Categoría.Considerada = structure(c(1L, 
    2L, 3L, 4L, 5L, 7L, 6L, 8L), .Label = c("Acaba la Unidad", 
    "España", "Francia", "ITalia", "Méjico", "No Cliker", "Otros Países", 
    "Usa App"), class = "factor"), Variación = structure(c(8L, 
    4L, 5L, 6L, 1L, 2L, 3L, 7L), .Label = c("-0.19%", "-0.46%", 
    "-2.32%", "0.31%", "0.46%", "0.7%", "1.15%", "2.08%"), class = "factor")), .Names = c("Variable", 
"Categoría.de.Referencia", "Categoría.Considerada", "Variación"
), row.names = c(NA, -8L), class = "data.frame")

您最好的选择可能是使用 sanitize.* 选项,例如:

> print.xtable(xtable(dat),include.rownames=F,
               sanitize.colnames.function=function(x)gsub("\."," ",x))

% latex table generated in R 3.2.1 by xtable 1.7-4 package
% Thu Aug 20 10:47:54 2015
\begin{table}[ht]
\centering
\begin{tabular}{llll}
  \hline
Variable & Categoría de Referencia & Categoría Considerada & Variación \ 
  \hline
Uso & No Acaba Unidad & Acaba la Unidad & 2.08\% \ 
  País & Brasil & España & 0.31\% \ 
  País & Brasil & Francia & 0.46\% \ 
  País & Brasil & ITalia & 0.7\% \ 
  País & Brasil & Méjico & -0.19\% \ 
  País & Brasil & Otros Países & -0.46\% \ 
  Clicker & Clicker & No Cliker & -2.32\% \ 
  App & No Usa App & Usa App & 1.15\% \ 
   \hline
\end{tabular}
\end{table}

来自?print.xtable

sanitize.text.function All non-numeric enteries (except row and column names) are sanitised in an attempt to remove characters which have special meaning for the output format. If sanitize.text.function is not NULL (the default), 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.colnames.function 相同。

另一个选择,如果你想彻底修改名字(这样你就不能 regex 像上面那样自由)是将 dat 转换为矩阵和设置 colnames:

datmat<-as.matrix(dat)
colnames(datmat)<-c("Variable","Categoría de Referencia",
                    "Categoría Considerada", "Variación")
print.xtable(xtable(datmat),include.rownames=F)