如何使用knitr和xtable旋转表的左边距名称? [英] How to rotate a table left margin name with knitr and xtable?
问题描述
我试图通过使用knitr和xtable将table命令的结果很好地打印在pdf上.
I'm trying to get the results of the table command nicely printed on a pdf by using knitr and xtable.
作为一个玩具示例,假设我要使用创建表
As a toy example let's say I want to get the table created with
表(c(2,5,5,5,5,7,7,7,7,NA),c(1,5,2,2,2,2,2,7,7,NA,NA))
table(c(2,5,5,5,5,7,7,7,7,NA),c(1,5,2,2,2,2,7,7,NA,NA))
我想得到这样的东西:
您可以看到var1逆时针旋转了90度.
我怎么才能得到它?类似的结果,行数更少或更多也是可以的.
As you can see var1 is rotated 90 degrees counterclockwise.
How can I get it?
Similar results, with less or more lines are OK too.
我正在尝试发现的不同方法.
我已经创建了该Rnw文件
I've being trying different methods I've found.
I've created this Rnw file,
\documentclass{article}
\usepackage{booktabs}
\usepackage{rotating}
\begin{document}
<<r table, results='asis', echo=FALSE>>=
library(knitr)
library(xtable)
var1 <- c(2,5,5,5,5,7,7,7,7,NA)
var2 <- c(1,5,2,2,2,2,7,7,NA,NA)
print(xtable(table(var1,var2)))
print.xtableFtable(xtableFtable(ftable(var1,var2),
method = "row.compact"))
print.xtableFtable(xtableFtable(ftable(var1,var2),
method = "row.compact"), rotate.rownames = TRUE)
print.xtable(xtable(table(var1,var2)), include.rownames=T,include.colnames=T)
@
\end{document}
您可以在下面看到我尝试的三种方法的结果.
You can see below the result of the three methods I've tried.
我没有得到预期的结果.
I can't get the expected result.
任何使用其他常见包装或kable的解决方案也都可以.
Any solution with other common package or kable it's OK too.
我猜可以用 \ rotatebox {90} 完成,但是我不知道如何强制xtable使用它,也不知道如何告诉xtable将左标题放在左边而不是只是在右上方.
I guess it could be done with \rotatebox{90} but I don't know how to force xtable to use it nor how to tell xtable to place the left title on the left instead of just being on the top-right.
推荐答案
这是一种可能性.免责声明:我是程序包的作者.
Here's one possibility. Disclaimer: I am the package author.
library(huxtable)
var1 <- c(2,5,5,5,5,7,7,7,7,NA)
var2 <- c(1,5,2,2,2,2,7,7,NA,NA)
tbl <- table(var1 = var1, var2 = var2)
ht <- as_hux(tbl)
ht <- cbind(rep('', 4), ht)
ht[2,1] <- 'var1'
ht <- rbind(rep('', 6), ht)
ht[2,2] <- '' # get rid of "rownames"
ht[1,3] <- 'var2'
colspan(ht)[1,3] <- 4
rowspan(ht)[3, 1] <- 3
rotation(ht)[3, 1] <- 90
right_border(ht)[,2] <- 1
bottom_border(ht)[5, -1] <- 1
bottom_border(ht)[2, -1] <- 1
ht
在rmarkdown PDF文档中使用时,将产生:
When used in an rmarkdown PDF document, this produces:
这篇关于如何使用knitr和xtable旋转表的左边距名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!