Search code examples
rfunctionmean

R Redefining base::mean() function to include is.finite() functionality


I would like to redefine the mean function (to apply it in a tabular() table) for it to omit all NA, NaN and Inf observations for a certain variable. I don't want to delete the whole row (observation) but rather have the mean formular simply calculate the mean for all values that are not NA, NaN, Inf.

Mean.new <- function(x) base::mean(x, na.rm=TRUE)

As far as I know does na.rm=TRUE in the standard mean() only remove NAs, not NaN and Inf.

Therefore, how do I add to the code above the functionality to check for is.finite() (which would exclude all NA, NaN, Inf)?

Thank you and best,

cork


Solution

  • With is.finite:

    mean_new <- function(x) {mean(x[is.finite(x)])}
    
    mean_new(c(NA,Inf,NaN,1,2))
    
    [1] 1.5