leeper / prediction

Tidy, Type-Safe 'prediction()' Methods
https://cran.r-project.org/package=prediction
Other
89 stars 14 forks source link

Expose mean or mode aggregating function #3

Closed leeper closed 7 years ago

leeper commented 7 years ago

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().