0

Some functions in R are able to take a data.frame as an argument, while having separate arguments whom can take the names of the data.frame (without having to quote them as strings).

A concrete example of this is the function qplot in the ggplot2 package:

myDF <- data.frame(values=rnorm(5*2), group=c(rep("A", 5), rep("B", 5)))
qplot(values, data=myDF, colour=group, geom="density")

qplot is able to take values and group and know that they are columns of myDF.

Now if I want to write a wrapper function that does some preprocessing before plotting, I lose that functionality:

# A silly example. But lets assume our dataframe has more than 1 group column
silly.wrapper <- function(dataframe, colour) {
  dataframe$values <- dataframe$values*2
  qplot(values*2, data=dataframe, geom="density", colour=colour)
}

now if i try to call silly.wrapper and give it colour=group it throws an error that the object group hasn't been declared (as you would expect):

# We have to call print because its a lattice plot so returned qplot won't render
# otherwise. Removing call to print still results in the same error.
print(silly.wrapper(myDF, colour=group))
Error in eval(expr, envir, enclos) : object 'group' not found
In addition: Warning message:
In eval(expr, envir, enclos) : restarting interrupted promise evaluation

I've also tried using ...:

silly.wrapper <- function(dataframe, ...) {
  dataframe$values <- dataframe$values*2
  qplot(values*2, data=dataframe, geom="density", ...)
}

But get the same error message.

This leads me to a more general question: How does one write a function, like qplot, that doesn't check for an object's existence until later, i.e. accessing it as a column of a dataframe?

Scott Ritchie
  • 10,293
  • 3
  • 28
  • 64
  • 2
    Don't use qplot, use ggplot and aes_string instead. – joran Sep 09 '13 at 03:03
  • 2
    Is that related to the answer? And if so can you elaborate? Otherwise it's not a particularly helpful comment. – Scott Ritchie Sep 09 '13 at 03:12
  • Yes, @Jorans comment is very much related to the answer. Look at how `qplot` and `aes` work........ – mnel Sep 09 '13 at 03:28
  • 1
    Re: your more general question, [this](http://stackoverflow.com/questions/8484664/how-do-you-code-an-r-function-so-that-it-knows-to-look-in-data-for-the-varia/8484970#8484970) this might be give you some insight into how a function can be constructed such that it searches for user-supplied names in a specified data.frame. – Josh O'Brien Sep 09 '13 at 03:33
  • It was the best I could do in the amount of time I had on just me phone. – joran Sep 09 '13 at 03:47
  • 1
    Have a look at http://adv-r.had.co.nz/Computing-on-the-language.html which describes the techniques that qplot uses, the problem that you encountered, and possible solutions. – hadley Sep 09 '13 at 12:27

0 Answers0