I'm trying to pass a dataframe column name to a function so that the same name can be passed to a ggplot function. I tried to pass the name as a string and then convert to a variable name. None of the methods work. Given below is an example of what I'm trying to do.
#
# Trying to use the variable directly
my.f <- function(var1, var2, data=NULL) {
p <- ggplot(data, aes(var1, var2))
p + geom_boxplot(outlier.colour = "green", outlier.size = 3)
}
# Retrieve the variable from the parent.frame.
my1.f <- function(var1, var2, data=NULL) {
var <- as.list(match.call()[-1])
p <- ggplot(data, aes(var$var1, var$var2))
p + geom_boxplot(outlier.colour = "green", outlier.size = 3)
# Create a new datafram. I can create a new data frame
# but, ggplot doesn't access those names still as only way to
# get variables names is as demonstrated above.
v1 <- deparse(substitute(var1))
v2 <- deparse(substitute(var2))
p.df <- data[, c(v1, v2)]
print(names(p.df))
p <- ggplot(p.df, aes(var$var1, var$var2))
p + geom_boxplot(outlier.colour = "green", outlier.size = 3)
}
#
# Create a simple data frame. The type is not significant
# as the objective is to show how to pass column names to a
# function
a <- runif(20)
b <- runif(20)
c <- runif(20)
my.df <- data.frame(a, b, c)
# my.f tries to use the variable name directly
my.f(a, b, my.df)
# my1.f retrieves the variable names from the parent.frame.
my1.f(a, b, my.df)
Both my.f
and my1.f
return the error
> my.f(a, b, my.df)
Error in eval(expr, envir, enclos) : object 'var1' not found
> my1.f(a, b, my.df)
[1] "a" "b"
Error in var$var1 : object of type 'closure' is not subsettable
In summary, I'm trying to pass data.frame column names to a function which in turn will pass the names to other internal functions (for eg. ggplot). Appreciate your help.