This vignette introduces nice and easy way to display grouped data frame created by dplyr::group_by
.
grouped_iris <- iris %>%
group_by(Species) %>%
slice(1, 2)
grouped_mtcars <- mtcars %>%
mutate(model = rownames(mtcars)) %>%
head %>%
select(model, cyl, mpg, disp, am) %>%
group_by(am, cyl)
Sepal.Length | Sepal.Width | Petal.Length | Petal.Width |
Species: setosa | |||
5.1 | 3.5 | 1.4 | 0.2 |
4.9 | 3.0 | 1.4 | 0.2 |
Species: versicolor | |||
7.0 | 3.2 | 4.7 | 1.4 |
6.4 | 3.2 | 4.5 | 1.5 |
Species: virginica | |||
6.3 | 3.3 | 6.0 | 2.5 |
5.8 | 2.7 | 5.1 | 1.9 |
Sepal.Length | Sepal.Width | Petal.Length | Petal.Width |
setosa | |||
5.1 | 3.5 | 1.4 | 0.2 |
4.9 | 3.0 | 1.4 | 0.2 |
versicolor | |||
7.0 | 3.2 | 4.7 | 1.4 |
6.4 | 3.2 | 4.5 | 1.5 |
virginica | |||
6.3 | 3.3 | 6.0 | 2.5 |
5.8 | 2.7 | 5.1 | 1.9 |
By specifying as_flextable(groups_to = 'merged')
, grouping variables are merged vertically. In this case, the default theme is changed to flextable::theme_vanilla
because the booktab theme is not intuitive.
Species | Sepal.Length | Sepal.Width | Petal.Length | Petal.Width |
setosa | 5.1 | 3.5 | 1.4 | 0.2 |
4.9 | 3.0 | 1.4 | 0.2 | |
versicolor | 7.0 | 3.2 | 4.7 | 1.4 |
6.4 | 3.2 | 4.5 | 1.5 | |
virginica | 6.3 | 3.3 | 6.0 | 2.5 |
5.8 | 2.7 | 5.1 | 1.9 |
am | cyl | model | mpg | disp |
1 | 6 | Mazda RX4 | 21.0 | 160 |
Mazda RX4 Wag | 21.0 | 160 | ||
Datsun 710 | 22.8 | 108 | ||
0 | 6 | Hornet 4 Drive | 21.4 | 258 |
Hornet Sportabout | 18.7 | 360 | ||
Valiant | 18.1 | 225 |
Grouping variables are moved to left by default. If you want to keep their positions, specify group_pos = 'asis'
.
grouped_mtcars %>%
as_flextable(groups_to = 'merged', groups_pos = 'asis') %>%
flextable::theme_vanilla()
model | cyl | mpg | disp | am |
Mazda RX4 | 6 | 21.0 | 160 | 1 |
Mazda RX4 Wag | 21.0 | 160 | ||
Datsun 710 | 22.8 | 108 | ||
Hornet 4 Drive | 6 | 21.4 | 258 | 0 |
Hornet Sportabout | 18.7 | 360 | ||
Valiant | 18.1 | 225 |