why can't I use element_text() in an ifelse()?

ggplot2, r

Solution

You can just not in the way you're trying to use it:

Here's an example of what I mean:

ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) + 
    geom_boxplot() + 
    theme(legend.text = element_text(size=ifelse(TRUE, 20, 10)))

It has to do with the `if` `else` you're using (`ifelse`) that's vectorized. I think you're after `if(){}else{}` as in:

ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) + 
    geom_boxplot()+ 
    theme(legend.text = if(TRUE){element_text(size=20)} else {element_text(size=10)})

though I really wouldn't format it this way but kept it to one line to allow comparison to your method.

The problem isn't `ggplot2` but your use of `ifelse`. Check out `?ifelse` and the documentation says:

 ‘ifelse’ returns a value with the same shape as ‘test’ which is
 filled with elements selected from either ‘yes’ or ‘no’ depending
 on whether the element of ‘test’ is ‘TRUE’ or ‘FALSE’.

In your question you show the output of `element_text(size=10)` that does not resemble `test` in structure.

Problem

How come I can't return an element_text() ``` > ifelse(TRUE,element_text(size=20),element_text(size=10)) [[1]] NULL ``` but I can do this? ``` > element_text(size=20) List of 8 $ family : NULL $ face : NULL $ colour : NULL $ size : num 20 $ hjust : NULL $ vjust : NULL $ angle : NULL $ lineheight: NULL - attr(*, "class")= chr [1:2] "element" "element_text" ```

Original source