簡體   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