Is it possible to have a header alignment in xtable which is different from the alignment used in the rest of the table? In my case, I want my header to be center aligned, but the table itself should be right aligned.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
To do that in LaTeX you stick your headers into a \multicolumn
thing to specify the alignment you want:
\begin{tabular}{rrr}
\hline
& \multicolumn{1}{c}{x} &\multicolumn{1}{c}{y} \\
\hline
1 & 1 & 0.17 \\
2 & 2 & 0.63 \\
3 & 3 & 0.95 \\
4 & 4 & 0.57 \\
5 & 5 & 0.65 \\
\hline
\end{tabular}
The print.xtable
function uses the names of the xtable
object as the headers. So if you rename your xtable
object:
> d=data.frame(x=1:5,y=runif(5)) # sample data frame
> dx=xtable(d) # make an xtable
> names(dx)=c("\\multicolumn{1}{c}{x}","\\multicolumn{1}{c}{y}")
then that's most of the work done, you just have to print it overriding the sanitization function of print.xtable
:
> print.xtable(dx,sanitize.colnames.function=function(x){x})
% latex table generated in R 2.15.1 by xtable 1.7-0 package
% Thu Feb 21 15:28:11 2013
\begin{table}[ht]
\begin{center}
\begin{tabular}{rrr}
\hline
& \multicolumn{1}{c}{x} & \multicolumn{1}{c}{y} \\
\hline
1 & 1 & 0.78 \\
2 & 2 & 0.34 \\
3 & 3 & 0.88 \\
4 & 4 & 0.45 \\
5 & 5 & 0.54 \\
\hline
\end{tabular}
\end{center}
\end{table}
otherwise it does
& $\backslash$multicolumn\{1\}\{c\}\{x\} & $\backslash$multicolumn\{1\}\{c\}\{y\} \\
How's that?
回答2:
Just to follow up on the answer by Spacedman (could not add a comment as I am reputationless ;)
Instead of doing sanitize.colnames.function=function(x){x}
you can do:
sanitize.colnames.function=function(x){paste0("\\multicolumn{1}{c}{",x,"}")}
This way you can skip renaming step. If you do/want to do other header "beautifications," they should be done before paste0
or between the commas (if short)