If the column names of a data.frame are started with numbers, or have spaces, aes_string() fails to handle them:
foo=data.frame(\"1
The original question asked how to modify a value of a variable so it is acceptable to ggplot() when the value is not know beforehand.
Write a function that adds back-ticks to the beginning and end of the value of the variable:
# ggName -> changes a string so it is enclosed in back-ticks.
# This can be used to make column names that have spaces (blanks)
# or non-letter characters acceptable to ggplot2.
# This version of the function is vectorized with sapply.
ggname <- function(x) {
if (class(x) != "character") {
return(x)
}
y <- sapply(x, function(s) {
if (!grepl("^`", s)) {
s <- paste("`", s, sep="", collapse="")
}
if (!grepl("`$", s)) {
s <- paste(s, "`", sep="", collapse="")
}
}
)
y
}
Examples:
ggname(12)
[1] 12
ggname("awk ward")
"`awk ward`"
l <- c("awk ward", "no way!")
ggname(l)
"`awk ward`" "`no way!`"