我需要修改lm(或最终loess)函数,以便我可以在ggplot2 geom_smooth(或stat_smooth)中使用它.
例如,这是stat_smooth通常使用的方式:
> qplot(data=diamonds, carat, price, facets=~clarity) + stat_smooth(method='lm')`
Run Code Online (Sandbox Code Playgroud)
我想定义一个自定义lm2函数作为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')
Run Code Online (Sandbox Code Playgroud)
请注意,我已将其用作method='lm2'参数stat_smooth.当我执行此代码时,获取错误:
eval中的错误(expr,envir,enclos):'nthcdr'需要一个列表来降低CDR
我不太懂.lm2在外面运行时,该方法非常有效stat_smooth.我玩了一下,我有不同类型的错误,但由于我不熟悉R的调试工具,我很难调试它们.老实说,我没有得到我应该把它放在return()电话里面.
使用...作为函数调用中的参数有些奇怪,我不完全理解(它与...作为列表类型对象有关).
这是一个通过将函数调用作为对象,将函数调用为lm然后在我们自己的调用者的上下文中评估调用来工作的版本.这个评估的结果是我们的返回值(在R中,函数中最后一个表达式的值是返回的值,所以我们不需要显式return).
foo <- function(formula,data,...){
print(head(data))
x<-match.call()
x[[1]]<-quote(lm)
eval.parent(x)
}
Run Code Online (Sandbox Code Playgroud)
如果要为lm调用添加参数,可以这样做:
x$na.action <- 'na.exclude'
Run Code Online (Sandbox Code Playgroud)
如果你想在调用lm之前将参数丢弃到foo,你可以这样做
x$useless <- NULL
Run Code Online (Sandbox Code Playgroud)
顺便说一句,geom_smooth并将stat_smooth任何额外的参数传递给平滑函数,因此如果只需要设置一些额外的参数,则无需创建自己的函数
qplot(data=diamonds, carat, price, facets=~clarity) +
stat_smooth(method="loess",span=0.5)
Run Code Online (Sandbox Code Playgroud)