flextable package in R is mainly used to create pretty tables for Word, HTML and PDF outputs.
Various functions in the package allows users to create tables, modify and format their content.
In this article, we will explore a few basic applications of the flextable package.
You can install flextable by the install.packages() function:
install.packages("flextable")
Let us have a look at the basic table we get using the flextable() function.
library(dplyr)
library(flextable)
data<-head(mtcars,5)
data %>% flextable()
mpg | cyl | disp | hp | drat | wt | qsec | vs | am | gear | carb |
21 | 6 | 160 | 110 | 3.9 | 2.6 | 16 | 0 | 1 | 4 | 4 |
21 | 6 | 160 | 110 | 3.9 | 2.9 | 17 | 0 | 1 | 4 | 4 |
23 | 4 | 108 | 93 | 3.8 | 2.3 | 19 | 1 | 1 | 4 | 1 |
21 | 6 | 258 | 110 | 3.1 | 3.2 | 19 | 1 | 0 | 3 | 1 |
19 | 8 | 360 | 175 | 3.1 | 3.4 | 17 | 0 | 0 | 3 | 2 |
set_caption() function allows you to change table headers. autofit() automatically computes and adjusts cell widths and heights to fit the size of the content.
data %>% flextable() %>%
set_caption(caption = "Introduction to flextable package") %>%
autofit()
mpg | cyl | disp | hp | drat | wt | qsec | vs | am | gear | carb |
21 | 6 | 160 | 110 | 3.9 | 2.6 | 16 | 0 | 1 | 4 | 4 |
21 | 6 | 160 | 110 | 3.9 | 2.9 | 17 | 0 | 1 | 4 | 4 |
23 | 4 | 108 | 93 | 3.8 | 2.3 | 19 | 1 | 1 | 4 | 1 |
21 | 6 | 258 | 110 | 3.1 | 3.2 | 19 | 1 | 0 | 3 | 1 |
19 | 8 | 360 | 175 | 3.1 | 3.4 | 17 | 0 | 0 | 3 | 2 |
align() function is used to set text alignment of selected rows and columns. Argument j is used to mention the columns we want to align, align to state the alignment and part to define the part of the table (‘all’, ‘body’, ‘header’, ‘footer’)
border_inner() and border_outer() are used for vertical & horizontal inner and outer borders respectively. For the same, we define a border using fp_border() function from package officer. In fp_border(), we specify color and width of the border we want.
bold() function is used to set bold font of selected rows and columns. bold=T sets the font as bold, i and j are the selected rows and columns respectively and part is the same as part argument of align() function as mentioned above.
library(officer)
std_border = fp_border(color="black", width = 1)
data %>% flextable() %>%
set_caption(caption = "Introduction to flextable package")%>%
align(j=1,align = "left", part = "all") %>%
align(j=2:4,align = "center", part = "all") %>%
border_inner(border = std_border) %>%
border_outer(border = std_border) %>%
bold(bold = T,part = "header") %>%
bold(bold = T,i=1:5,j=1,part = "body") %>%
autofit()
mpg | cyl | disp | hp | drat | wt | qsec | vs | am | gear | carb |
21 | 6 | 160 | 110 | 3.9 | 2.6 | 16 | 0 | 1 | 4 | 4 |
21 | 6 | 160 | 110 | 3.9 | 2.9 | 17 | 0 | 1 | 4 | 4 |
23 | 4 | 108 | 93 | 3.8 | 2.3 | 19 | 1 | 1 | 4 | 1 |
21 | 6 | 258 | 110 | 3.1 | 3.2 | 19 | 1 | 0 | 3 | 1 |
19 | 8 | 360 | 175 | 3.1 | 3.4 | 17 | 0 | 0 | 3 | 2 |