Just for clarification, not intended to reopen, as I will start a follow-up question:
- This not a question about using an
ifelse
indplyr
. - This is a question about passing by an argument in a custom function. This is important for certain (not mentioned) reasons!
Original question:
I have this example with the mtcars
dataset:
- Where basically the dataframe is filtered and then plotted.
- I wonder if it is possible to make the plot of the unfiltered data by this function ignoring the filtering variable
z
:
# create a custom function
my_function <- function(df, x, y, z) {
df %>%
filter(am == z) %>%
ggplot(aes(x = {{x}}, y={{y}}))+
geom_col()
}
apply function with filter am==0 <- WORKS
my_function(mtcars, cyl, mpg, 0)
apply function with filter am==1 <- WORKS
my_function(mtcars, cyl, mpg, 1)
would like to ignore the filter argument to get plot of all data <- WORKS NOT
my_function(mtcars, cyl, mpg)
Error in `filter()`:
! Problem while computing `..1 = am == z`.
Caused by error:
! argument "z" is missing, with no default