I would like to build tables of cumulative percentages using the expss package, including both ascending (0% -> 100%) and descending (100% -> 0%) orders. There is already an existing function (namely fre()
) for ascending order, although the resulting table is not much customizable.
I would like to include these calculations inside a tab_stat_fun
instruction, and managed to get to the desired output for unweighted datasets. Consider the following example (infert
dataset):
infert %>%
tab_cells(age) %>%
tab_cols(total()) %>%
tab_stat_cases(label="N", total_row_position="above", total_statistic="u_cases", total_label="TOTAL") %>%
tab_stat_cpct(label="%Col.", total_row_position="above", total_statistic="u_cpct", total_label="TOTAL") %>%
tab_stat_fun(label="% Asc.", function(x){100*cumsum(table(sort(x)))/sum(table(sort(x)))}) %>%
tab_stat_fun(label="% Desc.", function(x){100-(100*cumsum(table(sort(x)))/sum(table(sort(x))))}) %>%
tab_pivot(stat_position="inside_columns")
Works great, but if I ever want to weigh those results by a numeric vector (for the sake of demonstration: infert$w <- as.vector(x=rep(2, times=nrow(infert)), mode='numeric')
), this will inevitably lead to an error since neither sum nor cumsum accept weights argument (as far as I know).
Is there a special built-in function that would do the trick? Or a combination of functions that may imply multiplying the age vector by the weight vector?