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')))