Reputation: 3126
library(crosstable)
ct1 = crosstable(mtcars2, c(disp, vs), by=am, total="both",
percent_pattern="{n} ({p_row}/{p_col})", percent_digits=0) %>%
as_flextable()
ct1
How can I easily change the value label from "NA" into "missing" instead?
Upvotes: 1
Views: 71
Reputation: 2132
ct1
is a "well behaved" df and if it's just a chr
label, why not str_replace_all
?
ct1 <- crosstable(
mtcars2, c(disp, vs), by = am,
total="both", percent_pattern = "{n} ({p_row}/{p_col})", percent_digits = 0)
new_ct1 <- ct1 %>%
mutate(across(
where(is.character),
\(x) str_replace_all(x, "\\(NA\\)", "(missing)")))
as_flextable(new_ct1)
Upvotes: 3
Reputation: 125268
From my understanding the labels for the summary function are hard-coded in the default summary function cross_summary
. But you can simply use copy &. paste to write your own version of the summary function or use a wrapper function to set your desired label:
library(crosstable)
cross_summary2 <- function(x, dig = 1, ...) {
c(
`Min / Max` = minmax(x, dig = dig, ...),
`Med [IQR]` = mediqr(x,
dig = dig, ...
), `Mean (std)` = meansd(x,
dig = dig,
...
), `N (missing)` = nna(x)
)
}
cross_summary3 <- function(x, dig = 1, ...) {
xx <- cross_summary(x, dig = dig, ...)
names(xx)[names(xx) == "N (NA)"] <- "N (missing)"
xx
}
crosstable(mtcars2, c(disp, vs),
by = am, total = "both",
funs = c(` ` = cross_summary2),
percent_pattern = "{n} ({p_row}/{p_col})",
percent_digits = 0
) |>
as_flextable()
crosstable(mtcars2, c(disp, vs),
by = am, total = "both",
funs = c(` ` = cross_summary3),
percent_pattern = "{n} ({p_row}/{p_col})",
percent_digits = 0
) |>
as_flextable()
Upvotes: 4