R - How to use xtable to print a table() and keeping the row and column margin titles?

I need to generate many small tables from pairs of vectors like this:

library(xtable)
input1 <- c(0,0,0,1,1,1,1,2,2,2,2)
input2 <- c(0,0,0,0,0,1,0,0,0,1,2)
result <- table(input1, input2)
xtable(result)

The console output is OK.
>result

       input2
input1 0 1 2
     0 3 0 0
     1 3 1 0
     2 2 1 1

But I'd like to get nice latex output instead.
xtable produces this code:

\begin{table}[ht]
\centering
\begin{tabular}{rrrr}
  \hline
 & 0 & 1 & 2 \\ 
  \hline
0 &   3 &   0 &   0 \\ 
  1 &   3 &   1 &   0 \\ 
  2 &   2 &   1 &   1 \\ 
   \hline
\end{tabular}
\end{table}

As you can see the "input1" and "input2" margin titles have dissapeared.
enter image description here

But I'd like to get something like this: (or with more lines if you think it looks nicer).
enter image description here

What command do I need to use in R in order to get it?

I've also tried with

 print(xtable(x), include.rownames=T, include.colnames=T, booktabs = TRUE)

But it doesn't make any difference. The problem is "xtable" removes the information.

If you don't mind using the huxtable package - I am the author - here is one way you could do it:


library(magrittr)
library(huxtable)

ht <- as_hux(result)
dnn <- names(dimnames(result))
ht %>% 
      insert_row(rep(dnn[1], ncol(.))) %>% 
      insert_column(rep(dnn[2], nrow(.))) %>% 
      merge_cells(1, 2:5) %>% 
      merge_cells(1:5, 1) %>% 
      set_rotation(1, 1, 90) %>% 
      set_bottom_border(1, 2, 0.4) %>% 
      set_right_border(1, 1, 0.4) %>% 
      quick_pdf()

Result:

image

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.