Search code examples
rroundingsummary

Summary R function: rounding values


I want to know if there is any possibility to change the round method of the summary r function for values like that:

> mean(c(1, 12,28,30, 34,25,35, 40))
[1] 25.625

> summary(c(1, 12,28,30, 34,25,35, 40))
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   1.00   21.75   29.00   25.62   34.25   40.00 

In the summary function, I want the mean to be rounded as 25.63 and not 25.62

have a nice day!


Solution

  • You can use the round2 function from here :

    round2 = function(x, n) {
      posneg = sign(x)
      z = abs(x)*10^n
      z = z + 0.5 + sqrt(.Machine$double.eps)
      z = trunc(z)
      z = z/10^n
      z*posneg
    }
    x <- c(1, 12,28,30, 34,25,35, 40)
    
    round(mean(x), 2)
    #[1] 25.62
    
    round2(mean(x), 2)
    #[1] 25.63
    
    round(summary(x), 2)
    #   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
    #   1.00   21.75   29.00   25.62   34.25   40.00 
    
    round2(summary(x), 2)
    #   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
    #   1.00   21.75   29.00   25.63   34.25   40.00