R語言學習筆記(二): 類與泛型函數


大多數R對象都是基於S3類(來源於第三代S語言),例如直方圖函數hist()輸出是一個包含多個組件的列表,它還有一個屬性(attribute),用來指定列表的類,即histogram類。

泛型函數

類用在泛型函數中,泛型函數是一個函數族,其中的每個函數都有相似的功能,但是適用於某個特定的類。比如summary(),它是生成摘要的函數族,R會為要處理的類尋找合適的摘要函數,並使用比列表更加合理的方式來展示。因此對於hist()和lm()它會調用不同的摘要函數。(lm是linear model的縮寫)
同樣的plot()也是這樣的。

> a <- hist(Nile)
> summary(a)
         Length Class  Mode     
breaks   11     -none- numeric  
counts   10     -none- numeric  
density  10     -none- numeric  
mids     10     -none- numeric  
xname     1     -none- character
equidist  1     -none- logical  
> plot(a)

> b <- lm(Nile~c(1:100))
> plot(b)
Hit <Return> to see next plot: 
Hit <Return> to see next plot: 
Hit <Return> to see next plot: 
Hit <Return> to see next plot:
> summary(b)

Call:
lm(formula = Nile ~ c(1:100))

Residuals:
    Min      1Q  Median      3Q     Max 
-483.71  -98.17  -23.21  111.40  368.72 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)    
(Intercept) 1056.4224    30.3377  34.822  < 2e-16 ***
c(1:100)      -2.7143     0.5216  -5.204 1.07e-06 ***
---
Signif. codes:  
0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 150.6 on 98 degrees of freedom
Multiple R-squared:  0.2165,	Adjusted R-squared:  0.2085 
F-statistic: 27.08 on 1 and 98 DF,  p-value: 1.072e-06


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM