2

I'm writting a function that needs to be able to map a user specified mapping to a user supplied data.frame, so it's not up to me to give the columns sensible names.

How can the call be made to map to a column named log(y)?

I thought this would be a case for aes_string but this doesn't work.

library(ggplot2)

df <- data.frame(
  gp = factor(rep(letters[1:3], each = 10)),
  y = rnorm(30)
)

names(df)[2] <- "log(y)"

ggplot(df, aes_string("gp", "log(y)")) +
  geom_point()
#> Error in FUN(X[[i]], ...): object 'y' not found

Created on 2019-03-12 by the reprex package (v0.2.1)

I also tried quotations but couldn't get it to work and I'm not sure whether this would be the right application...

I also cannot map the column by df$'log(y)' since within my function the plot call is evaluated on two different data sets, both containing a log(y) column.

Any help would be greatly appreciated. Thanks.

  • 7
    R uses backticks for non-standard names. `aes(gp, \`log(y)\`)` will work. – Gregor Thomas Mar 12 '19 at 16:56
  • One possible dupe is [this](https://stackoverflow.com/q/12744282/903061), it's pretty space-focused so there might be a better one out there... – Gregor Thomas Mar 12 '19 at 16:58
  • 1
    The comment regarding the use of backticks is correct. However, this is just using non-standard names and you may potentially have problems with other packages. They may allow non-standard names, they may convert them to standard names, or they may fail strangely. Instead of naming the column `log(y)` you could use a standard name and then change the axis name using `ggplot(...) + ylab("log(y)")` – Adam Sampson Mar 12 '19 at 17:02
  • In addition to the fact that you're likely to have problems (such as this one) by trying to use non-standard names, `aes_string` is also being [deprecated](https://ggplot2.tidyverse.org/reference/aes_.html) in favor of tidyeval. When I need to make note of an operation that was done on a column like this, I just give it a name like `log_y` and set the `labs` with a presentation version (like "log(y)" – camille Mar 12 '19 at 18:10
  • use `!!` and `sym` from `rlang` package - `ggplot(df, aes(!!sym("gp"), !!sym("log(y)"))) + geom_point()` – Croote Mar 13 '19 at 04:02

0 Answers0