0

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.

donnie
  • 2,981
  • 2
  • 16
  • 24
  • 1
    Take a look at `aes_string` in `ggplot2`. – krlmlr Mar 23 '15 at 10:12
  • Yes, thank you. I didn't notice aes_string as I was looking for a way to pass variables to a function which can be used for calling other library functions. Though I'm still not clear about that, my current problem is solved. – donnie Mar 23 '15 at 11:10

0 Answers0