[R] How to latex tables?
Marc Schwartz
marc_schwartz at comcast.net
Sat May 5 18:35:01 CEST 2007
On Sat, 2007-05-05 at 09:43 -0400, steve wrote:
> Suppose I have a table constructed from structable or simply just an
> object of class table. How can I convert it to a latex object? I looked
> in RSiteSearch, but only found info about matrices or data frames.
>
> Steve
>
>
> For example, here is a table t2
>
> > str(t2)
> table [1:2, 1:2, 1:2] 6 8 594 592 57 ...
> - attr(*, "dimnames")=List of 3
> ..$ Hospital : chr [1:2] "A" "B"
> ..$ Survival : chr [1:2] "Died" "Survived"
> ..$ Condition: chr [1:2] "Good" "Poor"
>
> Here's what happens with latex(t2):
>
> latex(t2)
> Error in x[, j] : incorrect number of dimensions
>
> Next, here's what happens with a structtable.
>
> > tab=structable(Hospital ~ Condition + Survival, data=t2)
> > tab
> Hospital A B
> Condition Survival
> Good Died 6 8
> Survived 594 592
> Poor Died 57 8
> Survived 1443 192
>
> If I use latex(tab) I get
>
> Error in dimnames(cx) <- list(rnam, nam) :
> length of 'dimnames' [1] not equal to array extent
> In addition: Warning messages: ...(deleted)...
You are trying to apply the latex() function to a 3 dimensional table. I
don't know that any of the generally available R functions to generate
LaTeX markup (eg. latex() or xtable()) have methods that support 3D
tables.
You could either generate multiple 2D tables and convert each separately
or write your own function to generate the LaTeX markup in a format that
you find suitable for your application.
One other possible option, which would still require some tweaking
depending upon your need, would be to use ftable() to format and convert
the 3D table to a 2D table and latex() that. For example, using the
UCBAdmissions dataset:
> str(UCBAdmissions)
table [1:2, 1:2, 1:6] 512 313 89 19 353 207 17 8 120 205 ...
- attr(*, "dimnames")=List of 3
..$ Admit : chr [1:2] "Admitted" "Rejected"
..$ Gender: chr [1:2] "Male" "Female"
..$ Dept : chr [1:6] "A" "B" "C" "D" ...
> ftable(UCBAdmissions)
Dept A B C D E F
Admit Gender
Admitted Male 512 353 120 138 53 22
Female 89 17 202 131 94 24
Rejected Male 313 207 205 279 138 351
Female 19 8 391 244 299 317
> library(Hmisc)
> latex(ftable(UCBAdmissions), file = "")
% latex.default(ftable(UCBAdmissions), file = "")
%
\begin{table}[!tbp]
\begin{center}
\begin{tabular}{rrrrrr}\hline\hline
\multicolumn{1}{c}{}&
\multicolumn{1}{c}{}&
\multicolumn{1}{c}{}&
\multicolumn{1}{c}{}&
\multicolumn{1}{c}{}&
\multicolumn{1}{c}{}
\\ \hline
$512$&$353$&$120$&$138$&$ 53$&$ 22$\\
$ 89$&$ 17$&$202$&$131$&$ 94$&$ 24$\\
$313$&$207$&$205$&$279$&$138$&$351$\\
$ 19$&$ 8$&$391$&$244$&$299$&$317$\\
\hline
\end{tabular}
\end{center}
\end{table}
HTH,
Marc Schwartz
More information about the R-help
mailing list