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

南笙酒味 提交于 2019-11-28 00:11:10

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/2370648/modify-lm-or-loess-function-to-use-it-within-ggplot2s-geom-smooth

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!