Reputation: 779
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.
Upvotes: 5
Views: 3772
Reputation: 33960
Use aes_string
, which allows you to pass a string name for the variable.
Upvotes: 6
Reputation: 482
You could use the package "dplyr" to re-name the var.name column to something generic (x) and then plot on x:
# also need to mutate data in this column
df[,column.index] <- df[,column.index] * 10
# ***NEW*** re-name column to generic name
df <- rename_(df, .dots=setNames(list(var.name), 'x'))
# generate plot
plot <- ggplot(df, aes(x=x))+geom_bar()
Upvotes: -3