This vignette introduces nice and easy way to display grouped data
frame created by dplyr::group_by
.
library(ftExtra)
library(dplyr)
<- iris %>%
grouped_iris group_by(Species) %>%
slice(1, 2)
<- mtcars %>%
grouped_mtcars mutate(model = rownames(mtcars)) %>%
%>%
head select(model, cyl, mpg, disp, am) %>%
group_by(am, cyl)
%>% as_flextable() grouped_iris
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 |
%>% as_flextable(hide_grouplabel = TRUE) grouped_iris
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 |
%>% as_flextable() grouped_mtcars
model | mpg | disp |
am: 1.0 | ||
cyl: 6.0 | ||
Mazda RX4 | 21.0 | 160 |
Mazda RX4 Wag | 21.0 | 160 |
cyl: 4.0 | ||
Datsun 710 | 22.8 | 108 |
am: 0.0 | ||
cyl: 6.0 | ||
Hornet 4 Drive | 21.4 | 258 |
cyl: 8.0 | ||
Hornet Sportabout | 18.7 | 360 |
cyl: 6.0 | ||
Valiant | 18.1 | 225 |
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.
%>%
grouped_iris as_flextable(groups_to = "merged")
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 |
%>%
grouped_mtcars as_flextable(groups_to = "merged") %>%
::theme_vanilla() flextable
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") %>%
::theme_vanilla() flextable
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 |