AlefSin
AlefSin

Reputation: 1105

How to pass column names to a function that processes data.frames

I'm plotting lots of similar graphs so I thought I write a function to simplify the task. I'd like to pass it a data.frame and the name of the column to be plotted. Here is what I have tried:

plot_individual_subjects <- function(var, data)
{
  require(ggplot2)

  ggplot(data, aes(x=Time, y=var, group=Subject, colour=SubjectID)) +
    geom_line() + geom_point() + 
    geom_text(aes(label=Subject), hjust=0, vjust=0)
}

Now if var is a string it will not work. It will not work either if change the aes part of the ggplot command to y=data[,var] and it will complain about not being able to subset a closure.

So what is the correct way/best practice to solve this and similar problems? How can I pass column names easily and safely to functions that would like to do processing on data.frames?

Upvotes: 5

Views: 1656

Answers (1)

joran
joran

Reputation: 173737

Bad Joran, answering in the comments!

You want to use aes_string, which allows you to pass variable names as strings. In your particular case, since you only seem to want to modify the y variable, you probably want to reorganize which aesthetics are mapped in which geoms. For instance, maybe something like this:

ggplot(data, aes_string(y = var)) + 
    geom_line(aes(x = Time,group = Subject,colour = SubjectID)) + 
    geom_point(aes(x = Time,group = Subject,colour = SubjectID)) + 
    geom_text(aes(x = Time,group = Subject,colour = SubjectID,label = Subject),hjust =0,vjust = 0)

or perhaps the other way around, depending on your tastes.

Upvotes: 10

Related Questions