how to filter, then pipe and use sum function?

Viewed 2698

For Example the following will not work:

data(mpg)

filter(mpg, manufacturer =="audi") %>%
    sum(.$cty)

However the following will work:

data(mpg)

x <- filter(mpg, manufacturer =="audi")

sum(x$cty)

I would like to get it all to work in a piping flow if possible.

2 Answers

You could use pull to get column as a vector and then use sum.

library(dplyr)

mpg %>%
  filter(manufacturer =="audi") %>%
  pull(cty) %>%
  sum
#[1] 317

Your attempt does not work because pipes send output of LHS as first argument to the function in RHS. So a dataframe is being passed as first argument in sum. It will work if you use {} around it.

filter(mpg, manufacturer =="audi") %>% {sum(.$cty)}

We could do this without the filter step by doing this in summarise itself

library(dplyr)
library(ggplot2)
mpg %>% 
   summarise(out = sum(cty[manufacturer == "audi"])) %>%
   pull(out)
 #[1] 317
Related