if_na
должен сделать трюк:
data%>%
tab_cells(
add_val_lab(if_na(var1 %to% var10, 999), c("<NA>" = 999))
) %>%
tab_cols(total(), var12) %>%
tab_stat_cpct() %>%
tab_pivot()
Да, это довольно многословно, и я собираюсь упростить его в будущих expss
версиях. Если вы не используете метки значений, вы можете отказаться от функции add_val_lab
. if_na(var1 %to% var10, '<NA>')
будет достаточно.
ОБНОВЛЕНИЕ 21.05
Код с общим процентом:
library(expss)
data(mtcars)
mtcars = apply_labels(mtcars,
mpg = "Miles/(US) gallon",
cyl = "Number of cylinders",
disp = "Displacement (cu.in.)",
hp = "Gross horsepower",
drat = "Rear axle ratio",
wt = "Weight (lb/1000)",
qsec = "1/4 mile time",
vs = "Engine",
vs = c("V-engine" = 0,
"Straight engine" = 1),
am = "Transmission",
am = c("Automatic" = 0,
"Manual"=1),
gear = "Number of forward gears",
carb = "Number of carburetors"
)
# create function which calculate single table with NA percent under the total
tab_with_na = function(x, weight = NULL) {
rbind(
cro_cpct(
list(unvr(x)), # list(unvr()) to completely drop variable labels
col_vars = "|",
weight = weight),
# calculate percent of NA
cro_mean(
list("<NA>" = unvr(is.na(x)*100)), # list(unvr()) to completely drop variable labels
col_vars = "|",
weight = weight)
)
}
mtcars %>%
tab_cells(am %to% carb) %>%
tab_cols(total(), vs) %>%
tab_stat_fun(tab_with_na) %>%
tab_pivot()