BrooklynSon
BrooklynSon

Reputation: 2103

how to filter, then pipe and use sum function?

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.

Upvotes: 9

Views: 5514

Answers (2)

akrun
akrun

Reputation: 887691

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

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389175

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)}

Upvotes: 13

Related Questions