2012-10-09 10 views
8

Chciałbym mieć wymiary oznaczone na moim wyjściu xtable. Jednak metoda tabeli xtable nie emituje wymiar etykiety nawet kiedy podać je ręcznie do table:Jak uzyskać dimnames w wynikach xtable.table?

set.seed(10) 
d <- data.frame(x=sample(1:4),y=sample(1:4)) 
tb <- with(d, table(d,dnn=c("Xs","Ys"))) 
> tb 
    Ys 
Xs 1 2 3 4 
    1 0 0 0 1 
    2 0 1 0 0 
    3 1 0 0 0 
    4 0 0 1 0 
> xtable(tb) 
% latex table generated in R 2.15.1 by xtable 1.7-0 package 
% Tue Oct 9 09:06:10 2012 
\begin{table}[ht] 
\begin{center} 
\begin{tabular}{rrrrr} 
    \hline 
& 1 & 2 & 3 & 4 \\ 
    \hline 
1 & 0 & 0 & 0 & 1 \\ 
    2 & 0 & 1 & 0 & 0 \\ 
    3 & 1 & 0 & 0 & 0 \\ 
    4 & 0 & 0 & 1 & 0 \\ 
    \hline 
\end{tabular} 
\end{center} 
\end{table} 

Inspekcja kodu dla xtable.table nie daje żadnych tajemnic. Skoro nie budujesz ich ręcznie za pomocą multirow, czy istnieje sposób na oznaczenie wymiarów?

Odpowiedz

4

Jedno rozwiązanie z Pakiet tables:

library(tables) 

tblr <- tabular((Xs = as.factor(x)) ~ (Ys = as.factor(y)), data = d) 
latex(tblr) 

\begin{tabular}{lcccc} 
\hline 
& \multicolumn{4}{c}{Ys} \\ 
Xs & 1 & 2 & 3 & \multicolumn{1}{c}{4} \\ 
\hline 
1 & $0$ & $0$ & $0$ & $1$ \\ 
2 & $0$ & $1$ & $0$ & $0$ \\ 
3 & $1$ & $0$ & $0$ & $0$ \\ 
4 & $0$ & $0$ & $1$ & $0$ \\ 
\hline 
\end{tabular} 
4

Nie tworzy nagłówków multirow lub multicolumn opartych na nazwach wymiarów, ale przynajmniej je wyświetla.

print(xtable(format(ftable(tb))), 
     include.rownames=FALSE, include.colnames=FALSE, 
     sanitize.text.function = function(x) {gsub('"',"",x)}) 

co daje

% latex table generated in R 2.15.1 by xtable 1.7-0 package 
% Tue Oct 09 11:28:33 2012 
\begin{table}[ht] 
\begin{center} 
\begin{tabular}{llllll} 
    \hline 
    \hline 
    & Ys & 1 & 2 & 3 & 4 \\ 
    Xs &  &  &  &  &  \\ 
    1 &  & 0 & 0 & 0 & 1 \\ 
    2 &  & 0 & 1 & 0 & 0 \\ 
    3 &  & 1 & 0 & 0 & 0 \\ 
    4 &  & 0 & 0 & 1 & 0 \\ 
    \hline 
\end{tabular} 
\end{center} 
\end{table} 

Można przywrócić poziome linie w "prawo" miejsce, a także:

print(xtable(format(ftable(tb))), 
     include.rownames=FALSE, include.colnames=FALSE, 
     sanitize.text.function = function(x) {gsub('"',"",x)}, 
     hline.after = c(-1, 2, nrow(tb)+2)) 

dając

% latex table generated in R 2.15.1 by xtable 1.7-0 package 
% Tue Oct 09 11:29:21 2012 
\begin{table}[ht] 
\begin{center} 
\begin{tabular}{llllll} 
    \hline 
     & Ys & 1 & 2 & 3 & 4 \\ 
    Xs &  &  &  &  &  \\ 
    \hline 
1 &  & 0 & 0 & 0 & 1 \\ 
    2 &  & 0 & 1 & 0 & 0 \\ 
    3 &  & 1 & 0 & 0 & 0 \\ 
    4 &  & 0 & 0 & 1 & 0 \\ 
    \hline 
\end{tabular} 
\end{center} 
\end{table} 
+0

Świetnie. Szkoda, że ​​R sprawia, że ​​drukowanie prostego stołu jest tak trudne. – skan

Powiązane problemy