rroundingtapply

Is there a function in R to connect tapply with round?


Probably the solution is simple, but I can't find it right now. I like to use tapply in descriptive-statistical analyses. For example:

tapply(dataframe1$Means, dataframe2$gender, function(x) {
  c(
    "mean" = mean(x, na.rm = TRUE),
    "sd" = sd(x, na.rm = TRUE),
    "med" = median(x, na.rm = TRUE),
    "min" = min(x, na.rm = TRUE),
    "max" = max(x, na.rm = TRUE)
  )
})

Now I would like to have the results rounded directly to two places, but without writing them to another or new object.

Thanks for tips


Solution

  • Is it what you are looking for? I added round(c(...), digits = 2) around the group of summary functions (mean, sd, etc.) so the function does the rounding inside tapply without creating a new object.

    Edit: better version without repeating the round() function.

    tapply(iris$Sepal.Length, iris$Species, 
           function(x){round(c("mean" = mean(x, na.rm = TRUE),
                         "sd" = sd(x, na.rm = TRUE), 
                         "med" = median(x, na.rm = TRUE), 
                         "min" = min(x, na.rm = TRUE), 
                         "max"= max(x, na.rm = TRUE)), digits = 2)})
    #> $setosa
    #> mean   sd  med  min  max 
    #> 5.01 0.35 5.00 4.30 5.80 
    #> 
    #> $versicolor
    #> mean   sd  med  min  max 
    #> 5.94 0.52 5.90 4.90 7.00 
    #> 
    #> $virginica
    #> mean   sd  med  min  max 
    #> 6.59 0.64 6.50 4.90 7.90
    

    Created on 2022-05-10 by the reprex package (v2.0.1)