tags:

views:

140

answers:

1

I need to modify the lm (or eventually loess) function so I can use it in ggplot2's geom_smooth (or stat_smooth).

For example, this is how stat_smooth is used normally:

> qplot(data=diamonds, carat, price, facets=~clarity) + stat_smooth(method='lm')`

I would like to define a custom 'lm2' function to use as value for the 'method' parameter in stat_smooth, so I can customize its behaviour.

> lm2 <- function(formula, data, ...)
  {
      print(head(data))
      return(lm(formula, data, ...))
  }
> qplot(data=diamonds, carat, price, facets=~clarity) + stat_smooth(method='lm2')

Note that I have used method='lm2' as parameter in stat_smooth. When I execute this code a get the error:

'Error in eval(expr, envir, enclos) : 'nthcdr' needs a list to CDR down'

Which I don't understand very well. The lm2 method works very well when run outside of stat_smooth. I played with this a bit and I have got different types of error, but since I am not comfortable with R' debug tools it is difficult for me to debug them. Honestly, I don't get what I should put inside the 'return()' call.

+2  A: 

There is some weirdness in using ... as an argument in a function call that I don't fully understand (it has something to do with ... being a list-type object).

Here is a version that works by taking the function call as an object, setting the function to be called to lm and then evaluating the call in the context of our own caller. The result of this evaluation is our return value (in R the value of the last expression in a function is the value returned, so we do not need an explicit return).

foo <- function(formula,data,...){
   print(head(data))
   x<-match.call()
   x[[1]]<-quote(lm)
   eval.parent(x)
}

If you want to add arguments to the lm call, you can do it like this:

x$na.action <- 'na.exclude'

If you want to drop arguments to foo before you call lm, you can do it like this

x$useless <- NULL

By the way, geom_smooth and stat_smooth pass any extra arguments to the smoothing function, so you need not create a function of your own if you only need to set some extra arguments

qplot(data=diamonds, carat, price, facets=~clarity) + 
  stat_smooth(method="loess",span=0.5)
Jyotirmoy Bhattacharya
Thank you!! nice answer, my problem was that I didn't know I had to call the match.call and how to use it. What I really wanted to do is to skip the evaluation of lm for datasets with too few points (this may happen when you do facets, see http://groups.google.com/group/ggplot2/browse_thread/thread/df6da9d72f0a1dbf# ) but I wanted to see a general case.
dalloliogm
In the end, I solved my problem by reporting it to the ggplot2's author and waiting for him to fix it.
dalloliogm