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)
grouped_iris %>% as_flextable()
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 |
grouped_iris %>% as_flextable(hide_grouplabel = TRUE)
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()
model |
mpg |
disp |
am: 1.000 | ||
cyl: 6.000 | ||
Mazda RX4 |
21.0 |
160 |
Mazda RX4 Wag |
21.0 |
160 |
cyl: 4.000 | ||
Datsun 710 |
22.8 |
108 |
am: 0.000 | ||
cyl: 6.000 | ||
Hornet 4 Drive |
21.4 |
258 |
cyl: 8.000 | ||
Hornet Sportabout |
18.7 |
360 |
cyl: 6.000 | ||
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") %>% flextable::theme_vanilla()
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 |