Use weighted.mean in summary_rows GT package

Viewed 85

I've been searching around for a solution to using weighted.mean with summary_rows in GT package.

summary_rows function only accepts functions in form foo(x), therefore functions with more variables such as weighted.mean(x,w) is not accepted.

When using summary_rows with groups, such as:

summary_rows(groups = T, columns = c, fns = list("average" = ~mean(.)),...)

It takes vector of values for each group and then runs them through the mean() function, resp. the list of chosen functions.

My solution to this is quite cumbersome. I wrote my own custom function, that takes the vector of values provided by summary_rows and compares it to expected vectors using if statements. This only works for single columns at a time so it is quite a lot of code, both in the custom functions and in the code for the GT table.

weighted_mean_age <- function (x) {
  if (all(x == some.data$age.column[some.data$group.column == "group name"])) {
    weighted.mean(x, some.data$no.occurences[some.data$group.column == "group name"])
  } else if (another vector) {
    And so on for every group.
  } 
}

Did anyone deal with the same problem, but came up with less cumbersome solution? Did I miss something in the GT package?

Thank you for your time and ideas.

0 Answers
Related