在sweave,xtable中,只旋转一些列名

Jep*_*sen 5 r rotation xtable

让我们说我想在s​​weave中制作一张桌子,像这样:

<<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)
@
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

现在,我想在FishBird的年代和左边的自由空间中拥有情节的标签,但没有旋转.我尝试查看xtable手册,但它没有显示如何只旋转一些列名.

cof*_*nky 4

这是一个解决方法。我首先将年份放入一列中,并定义自己的函数来操作列名称。rotated[1]这允许我用其他名称替换第一个列名称(在我的代码示例中:) 。

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}
Run Code Online (Sandbox Code Playgroud)

请注意,您仍然可以拥有行名称。下面的方法也同样有效:

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="&")))} 
)
Run Code Online (Sandbox Code Playgroud)