Drawing on the discussion on conditional dplyr evaluation I would like conditionally execute a step in pipeline depending on whether the reference column exists in the passed da
Because of the way the scopes here work, you cannot access the dataframe from within your if
statement. Fortunately, you don't need to.
Try:
mtcars %>%
filter(am == 1) %>%
filter({if("cyl" %in% names(.)) cyl else NULL} == 4)
Here you can use the '.
' object within the conditional so you can check if the column exists and, if it exists, you can return the column to the filter
function.
EDIT: as per docendo discimus' comment on the question, you can access the dataframe but not implicitly - i.e. you have to specifically reference it with .