Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to filter, then pipe and use sum function?

Tags:

r

tidyverse

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.

like image 255
Angel Cloudwalker Avatar asked Feb 28 '20 00:02

Angel Cloudwalker


1 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)}
like image 87
Ronak Shah Avatar answered Sep 22 '22 08:09

Ronak Shah