Just as the title says, I'm trying to conditionally add a mutate step to my dplyr pipe. But I'm getting errors. Is there a tidy solution? Here's a simple example...
max.mpg <- 50
mtcars %>%
{
if(!!max.mpg > 10) mutate(foo = 1) else .
}
But the above generates the following error:
no applicable method for 'mutate' applied to an object of class "c('double', 'numeric')"
What I'm trying to do is add a new variable to the mtcars data frame--but only upon a given condition. If the condition is FALSE, then I just want the original data frame returned.
Interestingly, if I change the above condition to evaluate as FALSE (such as by writing, if(!!max.mpg > 60)), then the script runs fine. So, the problem indeed appears to reside in the mutate verb.
Finally, and in case it greatly affects the solution, I've got the above embedded inside a custom function. But I think if I can get the simple script correct in the above, I can work the rest out.
Any suggestions?