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

前端 未结 1 458
余生分开走
余生分开走 2020-12-17 21:52

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

<
相关标签:
1条回答
  • 2020-12-17 22:50

    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)
    
    0 讨论(0)
提交回复
热议问题