leeper / prediction

Tidy, Type-Safe 'prediction()' Methods

Home Page:https://cran.r-project.org/package=prediction

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Expose mean or mode aggregating function

leeper opened this issue · comments

A common need is to aggregate a data.frame to create column means (or medians), but appropriately handle factor, logical, and other non-numeric variable classes (i.e., aggregate to their mode rather than their [undefined] mean/median). A common use case for this is getting something like the "average prediction" or "marginal effect at means" (MEM).

I don't really want to implement either of those things specifically, but having a function to do them can be useful. For example, I have a function for this internally in margins::cplot():

mean_or_mode <- function(x) {
  if (is.factor(x)) {
    factor(names(sort(table(x), descending = TRUE))[1L], levels = levels(x))
  } else {
    mean(x, na.rm = TRUE)
  }
}

I should move it here, make it a bit more robust, and export it. Then call it from cplot().