R using ggplot2: "Error in value == "primary" : comparison is not allowed for expressions"

649 views Asked by At

I am attempting to change the labels in the handy facet plot available in R with ggplot using a function that I created, facet_labeller:

#This function will map a new name to the category labels
facet_labeller <- function(var, value){
  value <- as.character(value)

  # Creates labels with superscript for 1st and 2nd solvation shells
  label_primary <- expression(1^{st} ~ Shell)
  label_secondary <- expression(2^{nd} ~ Shell)

  if (var=="solvent") {
    value[value=="meoh"] <- "Methanol"
    value[value=="water"]   <- "Water"
  }
  if (var=="shell") {
    value[value=="secondary"] <- label_secondary
    value[value=="primary"] <- label_primary
  }
  if (var=="ion") {
    value[value=="Cl"] <- "Cl"
    value[value=="Na"] <- "Na"
  }
  return(value)
}

When the function is called by facet_grid:

facet_grid(shell + ion ~ solvent, scales="free_y", labeller=facet_labeller)

I get the error "Error in value == "primary" : comparison is not allowed for expressions"

I do not understand at all why this is occurring. Changing the line cited by the error will fix things and allow the plot to be created; for example, I can simply comment that line out, or I can put a string instead of the 'label_primary' variable. I need to use the expression, however, because of the superscripts.

Why is this happening? Why doesn't it happen with just one check in that if block? How can I get this to work? Any help would be greatly appreciated - I am at a total loss.

1

There are 1 answers

1
tegancp On BEST ANSWER

The cause of the error:

At the beginning of the function call, the elements of value all have class "character". But when you hit

    value[value=="secondary"] <- label_secondary

a bunch of those elements get replaced by expressions. So when you then try to do

    value[value=="primary"] <- label_primary

R is trying to compare some expressions to strings, but it doesn't know how to do comparison with expressions, so it just complains and stops working.

how to fix it:

Try replacing the block:

if (var=="shell") {
    value[value=="secondary"] <- label_secondary
    value[value=="primary"] <- label_primary
}

with:

if (var=="shell") {
    primary_values <- value=="primary"
    value[-primary_values] <- label_secondary
    value[primary_values] <- label_primary
}

This just checks each element once, before anything has been changed, so it avoids trying to do comparisons with expressions.