gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 20:17:53 25 4
gpt4 key购买 nike

假设我想在 sweave 中制作一个表格,如下所示:

<<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

现在,我想在 FishBird 的年份和左侧的自由空间中添加绘图的标签,但不旋转。我尝试查看 xtable 手册,但它没有显示如何仅旋转某些列名称。

最佳答案

这里有一个解决方法。我首先将年份放入一列中,并定义自己的函数来操作列名称。这允许我用其他名称替换第一个列名称(在我的代码示例中: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}

请注意,您仍然可以拥有行名称。以下内容也同样有效:

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="&")))}
)

关于r - 在sweave、xtable中,只旋转一些列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43734060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com