Reputation: 78927
How can I get this
library(dplyr)
library(flextable)
mtcars %>%
select(mpg, cyl, am) %>%
group_by(cyl, am) %>%
summarise(mean_mpg = mean(mpg),
sd_mpg = sd(mpg)) %>%
flextable()
To this:
Upvotes: 2
Views: 743
Reputation: 10675
You can also use tabulator()
+as_flextable()
functions:
library(dplyr)
library(flextable)
mtcars %>%
select(mpg, cyl, am) %>%
group_by(cyl, am) %>%
summarise(mean_mpg = mean(mpg),
sd_mpg = sd(mpg)) %>%
tabulator(rows = "cyl", columns = "am",
`μ` = as_paragraph(mean_mpg),
`σ` = as_paragraph(sd_mpg)) |>
as_flextable()
Upvotes: 2
Reputation: 912
We need tidyr::pivot_wider()
and ftExtra::span_header()
. If you wish to make the empty spaces between column use "empty" col_keys in flextable
.
library(tidyr)
library(dplyr)
library(flextable)
mtcars %>%
select(mpg, cyl, am) %>%
group_by(cyl, am) %>%
summarise(mean_mpg = mean(mpg),
sd_mpg = sd(mpg)) %>%
pivot_wider(names_from = am, values_from = c(mean_mpg, sd_mpg), names_glue = "am {am}.{.value}", names_vary = "slowest") %>%
flextable(col_keys = c(names(.)[1],"blank1",names(.)[2:3], "blank2", names(.)[4:5] )) |>
ftExtra::span_header(sep = "\\.") |>
empty_blanks()
Upvotes: 1