xtable右对齐并设置宽度Rmarkdown

时间:2016-10-21 10:04:46

标签: r r-markdown xtable

我有一个数据框,我希望在Rmarkdown中将其转换为具有正确对齐的表格

---
title: "Test"
output: 
  pdf_document
---

```{r testing, results='asis'}
library(xtable)
df <- structure(list(ID = c(101L, 102L, 103L, 104L, 105L, 106L), 
                       Gr1 = c(10.76,983.4, 34.000, 20, 23.8457, 13.32),
                       Gr2 = c(NA,NA, NA, 20L, NA, NA)
                       ), 
                  .Names = c("ID", "Grade1", "Grade2"), 
                  class = c("tbl_df", "data.frame"), 
                  row.names = c(NA, -6L))
xtable(df,
       align = c('l', 'p{1.5in}', rep('r{0.5in}',2)), 
       digits=c(0,0,1,0))
```

这给了我rep('r{0.5in}',2)

的错误
! LaTeX Error: Illegal character in array arg.

我也尝试过:align = c('l|', 'p{1.5in}|', rep('R{0.5in}|',2))

以下工作正常:align = c('l', 'p{1.5in}', rep('p{0.5in}',2))

The data isn't right aligned

但数据是左对齐的

2 个答案:

答案 0 :(得分:1)

这是你桌子的近似值。我不知道我的宽度是完全正确的。显然pixiedust发生了一些可疑的事情,因为当我将width_units"cm"更改为"in"时,我会得到一张太宽的表格。

---
title: "Test"
output: 
  pdf_document
header-includes: 
- \usepackage{amssymb} 
- \usepackage{arydshln} 
- \usepackage{caption} 
- \usepackage{graphicx} 
- \usepackage{hhline} 
- \usepackage{longtable} 
- \usepackage{multirow} 
- \usepackage[dvipsnames,table]{xcolor} 
---

```{r testing, results='asis'}
library(pixiedust)
df <- structure(list(ID = c(101L, 102L, 103L, 104L, 105L, 106L), 
                       Gr1 = c(10.76,983.4, 34.000, 20, 23.8457, 13.32),
                       Gr2 = c(NA,NA, NA, 20L, NA, NA)
                       ), 
                  .Names = c("ID", "Grade1", "Grade2"), 
                  class = c("tbl_df", "data.frame"), 
                  row.names = c(NA, -6L))
dust(df, keep_rownames = TRUE,
     float = FALSE) %>%
  sprinkle_colnames(.rownames = "") %>%
  medley_bw() %>%
  sprinkle_table(cols = ".rownames",
                 border = "right") %>%
  sprinkle_table(cols = c("Grade1", "Grade2"),
                 halign = "right") %>%
  sprinkle(cols = c("ID", "Grade1", "Grade2"),
           width = c(1.5, 0.05, 0.05),
           width_units = "cm",
           na_string = "",
           recycle = "cols") %>%
  sprinkle(cols = "Grade1",
           fn = quote(sprintf("%.1f", value)))

```

答案 1 :(得分:1)

解决了,我必须创建两个包含文件来注入必要的乳胶。首先在markdown文件上更新YAML:

---
title: "Test something"
output: 
  pdf_document:
    includes:
      in_header: preamble-latex.tex
      before_body: prebody-latex.tex
---
<SNIP, SEE ABOVE>

然后创建preamble-latex.tex以加载数组包

\usepackage{array}

创建prebody-latex.tex以存储新列命令

\newcolumntype{R}[1]{>{\raggedleft\let\newline\\\arraybackslash\hspace{0pt}}p{#1}}