Question

I have based my code on this example on stackoverflow. My first attempt works fine, as shown here: enter image description here

Then I tried doing the same with three groups. I am grouping like this:

df.m <- transform(df.m, facet=ifelse(df.m$variable %in% c(var11, var12), 'One',
                                 ifelse(df.m$variable %in% c(var21, var22), 'Two', 'Three')))
g <- ggplot(df.m, aes(group=facet, x=Years, y=value, colour=variable, shape=variable))
g <- g + geom_point() + facet_wrap(~facet)

With this code, I just end up with a single plot with all the variables. No faceting happens. I think I am doing something wrong with the ifelse, but I'm not sure.

As requested, this is the output of head(df.m):

  Years variable     value facet
1  1997     var11 0.1245161     One
2  1998     var11 0.1154599     One
3  1999     var11 0.1151908     One
4  2000     var11 0.1209199     One
5  2001     var11 0.1321990     One
6  2002     var11 0.1476364     One
Was it helpful?

Solution

So, the problem is because you are missing the quotes in the vector you are comparing against with %in%. But the reason you were getting error messages is a bit more complex than that. You must have objects in your workspace named var11, var12, etc.

Starting with a clean workspace:

require(reshape2)
dat = data.frame(ID = rnorm(10), var11 = rnorm(10), 
               var12 = rnorm(10), var21 = rnorm(10), var22 = rnorm(10), 
               var13 = rnorm(10), var23 = rnorm(10)) 
df.m = melt(dat, id.vars = 1)

If I do this, I get an error message when I run transform:

dfm2 = transform(df.m, facet=ifelse(variable %in% c(var11, var12), 'One',
                                 ifelse(variable %in% c(var21, var22), 'Two', 'Three')))
Error in match(x, table, nomatch = 0L) : object 'var11' not found

Now I create some vector objects with the same names in my workspace:

var11 = 1
var12 = 2
var21 = 1
var22 = 2
var13 = 1

dfm2 = transform(df.m, facet=ifelse(variable %in% c(var11, var12), 'One',
                                 ifelse(variable %in% c(var21, var22), 'Two', 'Three')))

Wah-lah, no error message and one level for the facet variable instead of three. Essentially, you never had any matches so the last level (Three) is assigned to everything.

You need those quotes to refer to a character vector instead of the objects.

transform(df.m, facet=ifelse(variable %in% c("var11", "var12"), 'One',
                                 ifelse(variable %in% c("var21", "var22"), 'Two', 'Three')))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top