Search code examples
rr-markdownflextable

Adjusting flextable position in rmarkdown


I'm using Flextable to make pretty tables in a Word doc that gets created in rmarkdown. The tables are all aligned in the center of the doc. I'd like them aligned on the left.

I know body_add_flextable has an align argument, but that function appears to be for inserting a flextable into an existing doc, and not for using within an rmarkdown file creating the doc.

I also have a reference_docx file where I can adjust styles, but tables get inserted as "normal" style, and I can't adjust the table without adjusting everything else in the doc with the "normal" style.

Here's an example rmarkdown file:

---
output: word_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(flextable)
```

```{r cars}
exampleDF <- data.frame("Col1" = c(1:3), "Col2" = c(4:6))
example.flex <- flextable(exampleDF)
example.flex
```

Also, I'm fairly new to using both rmarkdown and Flextable, and this is my first StackOverflow question. So all kinds of apologies if this is a stupid/poorly phrased question.


Solution

  • Dunno if this is a new feature, but you can do this following the online vignette, by adding ft.align = ... to the chunk options.

    I think the same holds true for word documents. I am posting this with html as an answer so I can share a screenshot as a result (don't use word) and also the question was not specifically for word (in the title).

    ---
    output: html_document
    ---
    
    ```{r setup, include=FALSE}
    library(flextable)
    
    ```{r cars, ft.align = "left"}
    exampleDF <- data.frame("Col1" = c(1:3), "Col2" = c(4:6))
    example.flex <- flextable(exampleDF)
    example.flex
    

    enter image description here