Search code examples
rggplot2dataframequotesquoting

ggplot handling quoted variable


I run into an unexpected issue in generating a ggplot() plot after operations done to a dataframe. I'm providing an illustrative example:

func <- function(){  
  library(ggplot2)
  df <- read.table(....)

  # Perform operation on df to retrieve column of interest index/number
  column.index <- regexpr(...)   
  # Now need to find variable name for this column
  var.name <- names(df)[column.index]
  # ...also need to mutate data in this column
  df[,column.index] <- df[,column.index] * 10

  # Generate plot
  plot <- ggplot(data, aes(x=var.name))+geom_bar()
  print(plot)
}

Here ggplot will throw an error since var.name is quoted, eg., "mpg". Any idea how to resolve this?

Edit: tested solutions from this question to no avail.


Solution

  • Use aes_string, which allows you to pass a string name for the variable.