I want to use an if statement to change the focus of the y aesthetic in ggplot:
ggplot(diamonds, aes(x = cut, y = ifelse(TRUE, sym("clarity"), sym("price")))) +
geom_col(position = "dodge")
But it gives me the following:
Don’t know how to automatically pick scale for object of type . Defaulting to continuous. Error in geom_col(): ! Problem while computing aesthetics. ℹ Error occurred in the 1st layer. Caused by error in compute_aesthetics(): ! Aesthetics are not valid data columns. âś– The following aesthetics are invalid: âś– y = ifelse(TRUE, sym("clarity"), sym("price")) ℹ Did you mistype the name of a data column or forget to add after_stat()?
>Solution :
This is a case where you need an if statement, not the ifelse function
ggplot(diamonds, aes(x = cut, y = if(TRUE) clarity else price)) +
geom_col(position = "dodge")
When you actually need control flow, you want if. ifelse is better when transforming vectors of values.
Because aes() uses non-standard evaluation. you can’t directly call something like
ggplot(diamonds, aes(x = cut, y = sym("clarity"))) +
geom_col(position = "dodge")
Rather you need to inject the value into the call with !!
ggplot(diamonds, aes(x = cut, y = !!sym("clarity"))) +
geom_col(position = "dodge")
so I guess if you really wanted to use ifelse you could just inject that value into the expression
ggplot(diamonds, aes(x = cut, y = !!ifelse(TRUE, sym("clarity"), sym("price")))) +
geom_col(position = "dodge")
Note that this doesn’t work with dplyr‘s more cautious dplyr::if_else because normally you don’t make a vector of symbols.
if you don’t bother with the symbols you can also do
ggplot(diamonds, aes(x = cut, y = ifelse(TRUE, clarity, price))) +
geom_col(position = "dodge")
because sym("clarity") isn’t exactly the same as clarity. The former needs to be evaluated to become the latter.