Skip to content

Instantly share code, notes, and snippets.

@vikjam
Last active February 10, 2019 19:36
Show Gist options
  • Save vikjam/95596bbd3b9398e2cfafa841ed706f89 to your computer and use it in GitHub Desktop.
Save vikjam/95596bbd3b9398e2cfafa841ed706f89 to your computer and use it in GitHub Desktop.
Summarize dplyr
Wrong mean: 5.84333333333333
Right mean: 5.936
The wrong mean didn't filter: 5.84333333333333
library(dplyr)
library(glue)
data(iris)
wrong_mean <- iris %>%
filter(iris$Species == "versicolor") %>%
summarize(avg_sepal_length = mean(iris$Sepal.Length))
right_mean <- iris %>%
filter(Species == "versicolor") %>%
summarize(avg_sepal_length = mean(Sepal.Length))
print(glue("Wrong mean: {wrong_mean}
Right mean: {right_mean}"))
unfiltered_mean <- mean(iris$Sepal.Length)
print(glue("The wrong mean didn't filter: {unfiltered_mean}"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment