1

Is there a way to use a structure like

grid.arrange(
    ifelse(somecondition,graph1,graph2),
    ifelse(somecondition2,graph3,graph4),
    ncol=2
)

where graphX is either a plot (created with ggplot2) or a grob defined previously. It looks like ifelse evaluates the grob object to something else (a dataframe ?) before printing so grid.arrange doesn't get the right input to work properly.

I also tried to store all the graph objects in a collection and use that within grid.arrange but coudn't get a proper data structure to work nicely.

Chapo
  • 2,563
  • 3
  • 30
  • 60
  • you should use `if() ... else ...` , not `ifelse`. It may also be easier to store the objects in a list, and pass that to the `grobs=` argument of `grid.arrange` – baptiste Oct 16 '15 at 01:37
  • Thks for your help. the `if() ... else ...` works. If you want to post it as an answer I'll accept it. I tried storing the objects in a list using `myList <- c(myList,additionalGraph)` but as the graphs are interpreted as lists themselves, it didn't pan out. Any better way to go about the list route ? – Chapo Oct 16 '15 at 02:51

1 Answers1

0

use if() ... else ..., not ifelse,

p1 = qplot(1,1)
p2 = qplot(1,2)
p3 = qplot(1,3)
p4 = qplot(1,4)

grid.arrange(
    if(1 == 2) p1 else p2,
    if(3 == 3) p3 else p4,
    ncol=2
)

If you want to store them in a list first,

pl = list(if(1 == 2) p1 else p2, if(3 == 3) p3 else p4)
grid.arrange(grobs=pl, ncol=2)
baptiste
  • 75,767
  • 19
  • 198
  • 294