R using ggplot2: "Error in value == "primary" : comparison is not allowed for expressions" -
i attempting change labels in handy facet plot available in r ggplot using function created, facet_labeller:
#this function map new name category labels facet_labeller <- function(var, value){ value <- as.character(value) # creates labels superscript 1st , 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 function called facet_grid:
facet_grid(shell + ion ~ solvent, scales="free_y", labeller=facet_labeller)
i error "error in value == "primary" : comparison not allowed expressions"
i not understand @ why occurring. changing line cited error fix things , allow plot created; example, can comment line out, or can put string instead of 'label_primary' variable. need use expression, however, because of superscripts.
why happening? why doesn't happen 1 check in if block? how can work? appreciated - @ total loss.
the cause of error:
at beginning of function call, elements of value
have class "character"
. when hit
value[value=="secondary"] <- label_secondary
a bunch of elements replaced expressions. when try
value[value=="primary"] <- label_primary
r trying compare expressions strings, doesn't know how comparison expressions, complains , stops working.
how fix it:
try replacing 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 checks each element once, before has been changed, avoids trying comparisons expressions.
Comments
Post a Comment