繁体   English   中英

修改lm或loess函数以在ggplot2的geom_smooth中使用它

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

我需要修改lm (或最终的loess )函数,以便我可以在ggplot2的geom_smooth (或stat_smooth )中使用它。

例如,这是正常使用stat_smooth方式:

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

我想定义一个自定义lm2函数作为stat_smooth method参数的stat_smooth ,所以我可以自定义它的行为。

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

请注意,我使用method='lm2'作为stat_smooth参数。 当我执行此代码时,获取错误:

eval中的错误(expr,envir,enclos):'nthcdr'需要一个列表来降低CDR

我不太懂。 stat_smooth之外运行时, lm2方法非常有效。 我玩了一下,我有不同类型的错误,但由于我不熟悉R的调试工具,我很难调试它们。 老实说,我没有得到我应该放在return()调用中。

使用...作为函数调用中的参数有些奇怪,我不完全理解(它与...作为列表类型对象有关)。

这是一个通过将函数调用作为对象,将函数调用为lm然后在我们自己的调用者的上下文中评估调用来工作的版本。 此评估的结果是我们的返回值(在R中,函数中最后一个表达式的值是返回的值,因此我们不需要显式return )。

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

如果要为lm调用添加参数,可以这样做:

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

如果你想在调用lm之前将参数丢弃到foo,你可以这样做

x$useless <- NULL

顺便说一下, geom_smoothstat_smooth将任何额外的参数传递给平滑函数,所以如果你只需要设置一些额外的参数,就不需要创建自己的函数

qplot(data=diamonds, carat, price, facets=~clarity) + 
  stat_smooth(method="loess",span=0.5)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM