Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
588 views
in Technique[技术] by (71.8m points)

r - modify lm or loess function to use it within ggplot2's geom_smooth

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's debug tools it is difficult for me to debug them. Honestly, I don't get what I should put inside the return() call.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...