Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In sweave, xtable, only rotate some column names

Tags:

r

rotation

xtable

Lets say i want to make a table in sweave, like this:

<<tab2.1 , results = "asis", echo=FALSE, warning=FALSE>>=
library(xtable)
df <- data.frame(Fish=1:5, Bird=11:15)

rownames(df) <- 2013:2017

print(xtable(df),
      rotate.colnames = TRUE)
@

enter image description here

Now, i would like to have the label of the plot in the free space above the years and left of the FishBird, but without rotation. I tried looking in the xtable manual, but it doesnt show how to only rotate some column names.

like image 304
Jeppe Olsen Avatar asked May 02 '17 09:05

Jeppe Olsen


1 Answers

Here is a workaround. I first put the years into a column, and define my own function to manipulate the column names. This allows me to replace the first column name (in my code example here: rotated[1]) with something else.

library(xtable)
df <- data.frame(rows = 2013:2017, Fish=1:5, Bird=11:15)
# note that the rownames have their own column

print(xtable(df), include.rownames = F, 
      sanitize.colnames.function = function(x){
        rotated <- paste("\\begin{sideways}", x, "\\end{sideways}") 
        # put all column names into sideways environments for the rotation.
        return(c("Need coffee!", paste(rotated[-1], collapse="&")))} 
        # replaces first column name with something else (not rotated).
)

\begin{table}[ht]
\centering
\begin{tabular}{rrr}
  \hline
Need coffee! & \begin{sideways} Fish \end{sideways} &\begin{sideways} Bird \end{sideways} \\ 
  \hline
2013 &   1 &  11 \\ 
  2014 &   2 &  12 \\ 
  2015 &   3 &  13 \\ 
  2016 &   4 &  14 \\ 
  2017 &   5 &  15 \\ 
   \hline
\end{tabular}
\end{table}

Note that you can still have your rownames. The following works just as well:

df <- data.frame(Fish=1:5, Bird=11:15)
rownames(df) <- 2013:2017
print(xtable(tibble::rownames_to_column(df)), include.rownames = F, 
      sanitize.colnames.function = function(x){
        rotated <- paste("\\begin{sideways}", x, "\\end{sideways}") 
        return(c("Need coffee!", paste(rotated[-1], collapse="&")))} 
)
like image 173
coffeinjunky Avatar answered Oct 09 '22 23:10

coffeinjunky