Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

ggplot2

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"
like image 407
nachocab Avatar asked Oct 19 '25 13:10

nachocab


1 Answers

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.

like image 93
Tyler Rinker Avatar answered Oct 22 '25 04:10

Tyler Rinker