stuski
stuski

Reputation: 199

R function using pipes

I am trying to build a function that uses pipes from the dplyr package but it won't work.

Can someone help me understand why I am getting an error message? Thanks

udf_ctable <- function(x){
  mtcars %>% group_by(x) %>% summarize(n=n())
  }
udf_ctable(cyl)

 Error in grouped_df_impl(data, unname(vars), drop) : 
  Column `x` is unknown 

Upvotes: 1

Views: 116

Answers (1)

RLave
RLave

Reputation: 8364

You need the !! beore the x, and call with "cyl":

udf_ctable <- function(x){
  mtcars %>% group_by(!!x) %>% summarize(n=n())
}
udf_ctable("cyl")

Here to know more about non standard evaluation with dplyr.

or, thanks to @IceCreamToucan:

udf_ctable <- function(x){
  x <- enquo(x) # quosure of x inside the function
  mtcars %>% group_by(!!x) %>% summarize(n=n()) # !! lets dplyr evaluate x
}
udf_ctable(cyl)

Upvotes: 8

Related Questions