0

I want to put ifelse opart inside dplyr case_when function:

library(mutate)

data(mtcars)

mtcars %>% 
  dplyr::mutate(myVar = case_when(
    mpg > 20 ~ ifelse(cyl == 6, 1, NA_real_),
    TRUE ~ 2
  ))

into it's own function:

myFun <- function(x) {
  ifelse(cyl == x, 1, NA_real_)
}

mtcars %>% 
  dplyr::mutate(myVar = case_when(
    mpg > 20 ~ myFun(6),
    TRUE ~ 2
  ))

But it returns an error:

Error in ifelse(cyl == x, 1, NA_real_) : object 'cyl' not found 

How should I rewrite the function to make it work?

BCPNAYAK
  • 177
  • 3
  • 4
  • 18
Mislav
  • 1,533
  • 16
  • 37
  • 1
    There is no `mutate` package. Please use `reprex`! – DHW Oct 22 '19 at 16:13
  • Possible duplicate of [How to pass dynamic column names in dplyr into custom function?](https://stackoverflow.com/questions/29678435/how-to-pass-dynamic-column-names-in-dplyr-into-custom-function) – DHW Oct 22 '19 at 16:20
  • This all definitely has to do with Tidyverse's non-standard evaluation (NSE); see https://adv-r.hadley.nz/quasiquotation.html. MyFun is not being executed within the scope of the black magic that converts the column names in the syntax into pointers to the data frame's columns, and I couldn't figure out how to get it to. Is there no better approach than that, though? Executing a function with NSE baked into it? – DHW Oct 22 '19 at 20:28
  • Better reference: http://adv-r.had.co.nz/Computing-on-the-language.html – DHW Oct 22 '19 at 20:44

0 Answers0