1

I am trying to write a function and pass in 2 parameters. I am getting an error and the function is not able recognize the 2nd parameter.

library(dplyr)

Test2 <- function(df, kk) {
  xx1 <- group_by_at(mtcars, vars(mpg, cyl, kk)) %>%
      summarise(FreqOG = length(cyl))
  xx1 <- data.frame(xx1)
}

yy1 <- Test2(mtcars,hp)
Dave2e
  • 22,192
  • 18
  • 42
  • 50
JK1185
  • 109
  • 1
  • 8

1 Answers1

4

You have to enquo the variable and use the !! operator:

library(dplyr)
Test2 <- function(df,kk) {
   kk<-enquo(kk)
   xx1 <- group_by_at(mtcars,vars(mpg,cyl,!!kk)) %>% summarise(FreqOG = length(cyl))
   xx1 <- data.frame(xx1)}

yy1 <- Test2(mtcars,hp)

This question may provide more background information: Why is enquo + !! preferable to substitute + eval

Dave2e
  • 22,192
  • 18
  • 42
  • 50