Why is mean ignoring trim parameter unless I use weird syntax?

Viewed 51

I'm trying to compute mean after dropping high and low values. But the following ignores the trim parameter:

library(tidyverse)
mtcars %>% 
  summarize(mpg = mean(mpg),
            mpg_trimmed = mean(mpg, trim = 0.05))
#>        mpg mpg_trimmed
#> 1 20.09062    20.09062

But the following works:

library(tidyverse)
mtcars %>% 
  summarize(mpg = mean(.$mpg),
            mpg_trimmed = mean(.$mpg, trim = 0.05))
#>        mpg mpg_trimmed
#> 1 20.09062    19.95333

Why do I need to use .$?

1 Answers

Because you are masking the original mpg variable (creating another in the scope of the function). Give a different name like mpg_mean. Remember that dplyr makes newly created variables immediately accessible.

library(dplyr)

mtcars %>% 
  summarize(mpg_mean = mean(mpg),
            mpg_trimmed = mean(mpg, trim = 0.05))
#>   mpg_mean mpg_trimmed
#> 1 20.09062    19.95333
Related