Search code examples
rr-markdownxtable

xtable align right and set width Rmarkdown


I have a dataframe that I want to turn into a table with right alignment in 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))
```

This gives me an error on the rep('r{0.5in}',2)

! LaTeX Error: Illegal character in array arg.

I've also tried: align = c('l|', 'p{1.5in}|', rep('R{0.5in}|',2))

The following works fine: align = c('l', 'p{1.5in}', rep('p{0.5in}',2))

The data isn't right aligned

But the data is left aligned


Solution

  • Solved, I have to create two include files to inject the necessary latex. First update the YAML on the markdown file:

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

    Then create preamble-latex.tex to load the array package

    \usepackage{array}
    

    And create prebody-latex.tex to store your new column command

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