为xtable生成的longtable设置列对齐和宽度

时间:2014-01-01 01:14:14

标签: r tex xtable longtable

请考虑以下MWE

library(xtable)
DF <- as.data.frame(UCBAdmissions)
print(xtable(DF, align="p{0.4\textwidth}|p{0.15\textwidth} p{0.15\textwidth} p{0.15\textwidth}"), sanitize.text.function = function(x){x}, 
      table.placement="!htp", include.rownames=FALSE, 
      tabular.environment='longtable',floating=FALSE)

我想设置longtable的对齐方式

\begin{longtable}{p{0.4\textwidth}|p{0.15\textwidth} p{0.15\textwidth} p{0.15\textwidth}}

当我尝试将参数传递给xtable对象时,我得到了

Warning message:
In .alignStringToVector(value) : Nonstandard alignments in align string
Error in print(xtable(DF, align = "p{0.4\textwidth}|p{0.15\textwidth} p{0.15\textwidth} p{0.15\textwidth}"),  : 
  error in evaluating the argument 'x' in selecting a method for function 'print': Error in `align<-.xtable`(`*tmp*`, value = "p{0.4\textwidth}|p{0.15\textwidth} p{0.15\textwidth} p{0.15\textwidth}") : 
  "align" must have length equal to 5 ( ncol(x) + 1 )

我知道我应该为第5列添加对齐(如何?)但我也不理解错误消息。我应该清理字符串吗?

1 个答案:

答案 0 :(得分:12)

我无法对此进行测试,但我认为您需要将标准R转义应用于字符串中的反斜杠,删除无关的“\”并添加缺少的“竖线”(|)。然后align<-成功,只有一个警告:

xtb <- xtable(DF, 
       table.placement="!htp", include.rownames=FALSE, 
       tabular.environment='longtable',floating=FALSE)
align(xtb) <- "p{0.4\\textwidth}|p{0.15\\textwidth}|p{0.15\\textwidth}| p{0.15\\textwidth}"
#Warning message:
#In .alignStringToVector(value) : Nonstandard alignments in align string
 print(xtb)

或者:

xtb <- xtable(DF, type="latex",
      table.placement="!htp", include.rownames=FALSE, 
      tabular.environment='longtable',floating=FALSE, align= c("p{0.15\\textwidth}", 
"p{0.4\\textwidth}", "p{0.15\\textwidth}|", "p{0.15\\textwidth}", "p{0.15\\textwidth}"
))