我想知道為什么自smooth()定義類的自定義函式不優先于stats::smooth(). 這是一個例子:
create_my_class = function(mydata){
class(mydata) = c("my_class", "data.frame")
return(mydata)
}
df = data.frame(x = rnorm(100), y = rnorm(100))
df = create_my_class(df)
現在,我知道我可以plot()為這個類定義一個函式,并且plot()當我傳遞一個myclass物件時它會取代其他方法:
library(ggplot2)
plot.my_class = function(data){
ggplot(data, aes(x,y))
geom_point()
}
plot(df)

但是為什么這種方法不適用于名為 的函式smooth.my_class()?例如,這個簡單的平滑函式:
smooth.my_class = function(data){
lm(y~x, data)
}
當運行時smooth(df)拋出錯誤“平滑錯誤(df):嘗試平滑非數字值”,如果我運行它是相同的stats::smooth(df)。
這里有更大的問題嗎?只能重新使用某些函式名稱來獲取自定義類嗎?
uj5u.com熱心網友回復:
是的,這里有一個更大的問題。如果你想定義一個特定的方法來處理一個特定的類,那么所討論的函式需要是一個泛型函式。
例如,查看 的函式定義print:
print
#> function (x, ...)
#> UseMethod("print")
這就是函式的全部內容print。當您print(object)在控制臺中鍵入時,此函式將執行,它所做的只是查找 的類object,將類名附加到單詞print并查找該函式。例如,如果object屬于“data.frame”類,則UseMethod("print")查找print.data.frame,如果存在,將使用您提供給 的引數呼叫它print。如果類不存在特定方法,則泛型函式具有(或應該具有)回退默認方法。
smooth您的自定義函式不起作用的原因smooth是它不是通用函式。當您運行時smooth,不會查找特定于類的方法,而您只會變得陳舊stats::smooth
不過,您可以創建smooth一個通用函式。以下應該為您的自定義類正確調度,在所有其他情況下默認為stats::smooth:
smooth <- function(x, ...) UseMethod("smooth")
smooth.my_class = function(data, ...){
lm(y~x, data)
}
smooth.default <- function(x, ...) stats::smooth(x, ...)
例如,如果我們在您的自定義類上嘗試它,我們會得到一個lm
smooth(df)
#>
#> Call:
#> lm(formula = y ~ x, data = data)
#>
#> Coefficients:
#> (Intercept) x
#> 0.07497 0.09133
但是在數字向量上呼叫它會呼叫stats::smooth
smooth(df$x)
#> 3RS3R Tukey smoother resulting from stats::smooth(x = x)
#> used 6 iterations
#> [1] 0.08976935 0.08976935 0.08976935 -0.19641797 -0.19641797 -0.19641797
#> [7] -0.19641797 0.02547707 0.08861531 0.08861531 -0.03327923 -0.09422650
#> [13] -0.09422650 -0.15654766 -0.15654766 -0.37095531 -0.49807061 -0.87394069
#> [19] -1.18237852 -1.18237852 -0.05479660 -0.05479660 -0.05479660 0.26811991
#> [25] 0.37611915 0.37611915 0.70314430 0.70314430 0.70314430 0.70314430
#> [31] 0.70314430 0.24278460 0.24278460 0.24278460 0.51725720 0.51725720
#> [37] 0.51725720 0.51725720 0.67223056 0.67223056 0.67223056 0.67223056
#> [43] 0.67223056 0.09257700 0.08426558 0.08426558 0.08426558 0.08426558
#> [49] 0.08426558 0.51762272 0.51762272 0.51762272 0.51762272 0.51762272
#> [55] 0.51762272 0.02758035 0.02758035 0.10725655 0.13239083 0.13239083
#> [61] 0.18802296 0.18802296 0.55088073 0.55088073 0.55088073 0.55088073
#> [67] 0.55088073 0.76919007 0.76919007 0.76919007 0.48469683 0.48469683
#> [73] -0.32896249 -0.32896249 -0.31640679 -0.28686752 -0.21660688 -0.21660688
#> [79] -0.21660688 -0.21660688 -0.87848779 -0.87848779 -0.87848779 -1.69139208
#> [85] -1.77982364 -1.77982364 -1.22898324 0.33751308 0.44113212 0.44113212
#> [91] 0.85571511 0.85571511 0.85571511 0.34594270 0.29631435 0.19705764
#> [97] -0.02076665 -0.02076665 -0.02076665 -0.02076665
由reprex 包(v2.0.1)于 2022-04-24 創建
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/463627.html
標籤:r
