# flextable overview

## Introduction

`flextable` can easily create reporting table from `data.frame`. You can merge cells, add header rows, add footer rows, change any format and specify how data should be displayed in cells. Tables content can also contain mixed type of content, text and images.

`flextable` objects can be rendered in HTML format, Microsoft Word, Microsoft PowerPoint and PDF.

> The following table is made with function `flextable` and dataset data:

    data <- iris[c(1:3, 51:53, 101:104),]
    data
    #>     Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
    #> 1            5.1         3.5          1.4         0.2     setosa
    #> 2            4.9         3.0          1.4         0.2     setosa
    #> 3            4.7         3.2          1.3         0.2     setosa
    #> 51           7.0         3.2          4.7         1.4 versicolor
    #> 52           6.4         3.2          4.5         1.5 versicolor
    #> 53           6.9         3.1          4.9         1.5 versicolor
    #> 101          6.3         3.3          6.0         2.5  virginica
    #> 102          5.8         2.7          5.1         1.9  virginica
    #> 103          7.1         3.0          5.9         2.1  virginica
    #> 104          6.3         2.9          5.6         1.8  virginica

Species |  | Sepal |  | Petal
| Length | Width |  | Length | Width
setosa |  | 5.1 | 3.5 |  | 1.4 | 0.2
| 4.9 | 3.0 |  | 1.4 | 0.2
| 4.7 | 3.2 |  | 1.3 | 0.2
versicolor |  | 7.0 | 3.2 |  | 4.7 | 1.4
| 6.4 | 3.2 |  | 4.5 | 1.5
| 6.9 | 3.1 |  | 4.9 | 1.5
virginica |  | 6.3 | 3.3 |  | 6.0 | 2.5
| 5.8 | 2.7 |  | 5.1 | 1.9
| 7.1 | 3.0 |  | 5.9 | 2.1
| 6.3 | 2.9 |  | 5.6 | 1.8

## Getting started

The main function is `flextable`.

`flextable` function is producing flexible tables where each cell can contain several chunks of text with their own set of formatting properties (bold, font color, etc.).

The function is using default values to format the table. It is also using a simple formatting function to create the paragraphs of text that will be rendered in each cell. All these default values can be modified after the flextable creation.

The following illustration is presenting most of the functions available to format a flextable:

Let’s have a step by step demo. First create a flextable and change header font in bold.

    library(flextable)
    library(officer)

    myft <- flextable(
      head(mtcars),
      col_keys = c("am", "carb", "gear", "mpg", "drat" ))
    myft

am | carb | gear | mpg | drat
1 | 4 | 4 | 21.0 | 3.90
1 | 4 | 4 | 21.0 | 3.90
1 | 1 | 4 | 22.8 | 3.85
0 | 1 | 3 | 21.4 | 3.08
0 | 2 | 3 | 18.7 | 3.15
0 | 1 | 3 | 18.1 | 2.76

flextable: it is creating a flextable object based on input data. Optional argument `col_keys` is used to only display a subset of columns.

Functions `theme_` are sugar functions whose role is to apply a set of formatting instructions to a flextable. For example, `theme_vanilla` set specific borders, right align paragraphs and make headers bold.

    myft <- theme_vanilla(myft)
    myft

am | carb | gear | mpg | drat
1 | 4 | 4 | 21.0 | 3.90
1 | 4 | 4 | 21.0 | 3.90
1 | 1 | 4 | 22.8 | 3.85
0 | 1 | 3 | 21.4 | 3.08
0 | 2 | 3 | 18.7 | 3.15
0 | 1 | 3 | 18.1 | 2.76

### Layout

Table layout can be modified. One can add or change header/footer rows, change cells height and width and merge cells.

Also, there is an important function named `autofit` (it adjusts widths and heights regarding to text widths and heights).

    myft <- merge_v(myft, j = c("am", "carb") )
    myft <- set_header_labels( myft, carb = "# carb." )
    myft <- autofit(myft)
    myft

am | # carb. | gear | mpg | drat
1 | 4 | 4 | 21.0 | 3.90
4 | 21.0 | 3.90
1 | 4 | 22.8 | 3.85
0 | 3 | 21.4 | 3.08
2 | 3 | 18.7 | 3.15
1 | 3 | 18.1 | 2.76

To learn more, see article about layouts.

### Formatting

> To learn more, see article about format.

Many sugar functions can be used to format flextables: `bg()`, `fontsize()`, `italic()`, `bold()`, `color()`, `padding()`…

Conditional formatting can be made by using the selector arguments. All formatting functions are accepting selector arguments.

    myft <- italic(myft, j = 1)
    myft <- bg(myft, bg = "#C90000", part = "header")
    myft <- color(myft, color = "white", part = "header")
    myft <- color(myft, ~ drat > 3.5, ~ drat, color = "red")
    myft <- bold(myft, ~ drat > 3.5, ~ drat, bold = TRUE)
    myft <- autofit(myft)
    myft

am | # carb. | gear | mpg | drat
1 | 4 | 4 | 21.0 | 3.90
4 | 21.0 | 3.90
1 | 4 | 22.8 | 3.85
0 | 3 | 21.4 | 3.08
2 | 3 | 18.7 | 3.15
1 | 3 | 18.1 | 2.76

### Keypoints

- A flextable is an object that will produce a reporting table from a `data.frame` object.

- A flextable is containing three parts, header, body and footer. By default, there is only one header row containing the names of the data.frame. The body part is containing data from the data.frame. The footer part is not implemented by default.

- Any formatting property related to text, paragraphs, cells in the table can be modified.

- A cell is made of one single paragraph of text. Paragraphs can contain several chunks of text with different formatting but also images.

- The dimensions of the flextable elements, widths of columns and heights of rows, are always defined. Beeing able to define the exact size necessary to display data on a single line is a choice made to make sure HTML, pptx, docx, images have all the same rendering, for that exact widths and heights were needed. In most of cases, you should not worry about that by only using `autofit()` as last operation. See functions `autofit()` and `dim_pretty()`.

- Columns to display (`col_keys`) are by default all columns of the data.frame but can be choosen from a subset of existing columns and also unexisting columns. Unexisting columns are containing blanks by default but this content can be customized.

## Flextable rendering

When working in RStudio, flextable will be printed in the rstudio viewer pane, the default format is HTML output.

We will use the following example:

    ft <- flextable(head(mtcars))
    ft <- autofit(ft)
    ft

mpg | cyl | disp | hp | drat | wt | qsec | vs | am | gear | carb
21.0 | 6 | 160 | 110 | 3.90 | 2.620 | 16.46 | 0 | 1 | 4 | 4
21.0 | 6 | 160 | 110 | 3.90 | 2.875 | 17.02 | 0 | 1 | 4 | 4
22.8 | 4 | 108 | 93 | 3.85 | 2.320 | 18.61 | 1 | 1 | 4 | 1
21.4 | 6 | 258 | 110 | 3.08 | 3.215 | 19.44 | 1 | 0 | 3 | 1
18.7 | 8 | 360 | 175 | 3.15 | 3.440 | 17.02 | 0 | 0 | 3 | 2
18.1 | 6 | 225 | 105 | 2.76 | 3.460 | 20.22 | 1 | 0 | 3 | 1

### R Markdown documents

One great feature of `flextables` is that it can be used in R Markdown documents; HTML, Word, PowerPoint and PDF outputs are managed with method `knitr::knit_print`.

Print the `flextable` object in the rmarkdown’s chunk as demonstrated in this document (…generated from an R Markdown document).

        ---
        title: 'flextable formatting'
        output: rmarkdown::html_document
        ---

        > this is how to print a flextable in a R Markdown document

        ```{r}
        library(flextable)
        ft <- flextable(head(mtcars))
        ft <- autofit(ft)
        ft
        ```

#### pandoc versions

Supported formats require some minimum pandoc versions:

R Markdown output | pandoc version | comment
--- | --- | ---
`rmarkdown::html_*` | >= 1.12 |
`rmarkdown::word_document` | >= 2.0 | require a recent RStudio (> june 2018)
`rmarkdown::powerpoint_presentation` | >= 2.4 | require pandoc installation
`rmarkdown::pdf_document` | >= 1.12 | produces an image - limited support

#### Notes about PDF

- Using flextable with template `pdf_document` is OK if the flextable fits on one single page. The PDF output is not a real latex output but a PNG image.
- The best option to produce PDF documents containing flextable objects is by using package `pagedown`. The only current known limitation is the inability to repeat header rows along pages when the table need more than a page.

#### Notes about rmarkdown::word_document

This note is only relevant when using flextable in an R Markdown document with Word output.

In some context, `officedown::rdocx_document()` will have to be used instead of `rmarkdown::word_document()`. This is because Word don’t store hyperlinks or images in the main document but store references. This is not managed by rmarkdown unless `officedown::rdocx_document()` is used.

If you don’t add images or hyperlinks in a flextable rendered by `officedown::rdocx_document()` then you can forget about that.

### PowerPoint or Word documents with officer

#### Simple export

Use function `save_as_docx` or `save_as_pptx` that lets users export flextable objects to PowerPoint or Word documents..

    docx_file <- tempfile(fileext = ".docx")
    pptx_file <- tempfile(fileext = ".pptx")
    # docx_file <- "example.docx"
    # pptx_file <- "example.pptx"
    save_as_docx("my table" = ft, path = docx_file)
    save_as_docx("my table" = ft, path = pptx_file)

#### In an interactive session

If you have a Word or PowerPoint client on your machine, you can use the `print` method with argument `preview` set to “pptx” or “docx”. It will produce and open a document where the table will be printed and ready to go to your clipboard.

    print(ft, preview = "docx")
    print(ft, preview = "pptx")

#### With package officer

To add these objects in PowerPoint or Word documents, use functions:

- `ph_with()` (PowerPoint)
- `body_add_flextable()` (Word)

    library(officer)

The following is producing a PowerPoint document:

    ppt <- read_pptx()
    ppt <- add_slide(ppt, layout = "Title and Content", master = "Office Theme")
    ppt <- ph_with(ppt, value = ft, location = officer::ph_location_left())

    print(ppt, target = "example.pptx")

The following is producing a Word document:

    doc <- read_docx()
    doc <- body_add_flextable(doc, value = ft)
    print(doc, target = "example.docx")

## As an image

To get an image file from a `flextable` object, use function `save_as_image`.

    img_file <- tempfile(fileext = ".png")
    save_as_image(ft, path = img_file)

flextable objects can also be ploted, see Render as image for more details.