1 / 13
文档名称:

R语言-第九章.ppt

格式:ppt   大小:34KB   页数:13页
下载后只包含 1 个 PPT 格式的文档,没有任何的图纸或源代码,查看文件列表

如果您已付费下载过本站文档,您可以点这里二次下载

分享

预览

R语言-第九章.ppt

上传人:2072510724 2018/10/17 文件大小:34 KB

下载得到文件列表

R语言-第九章.ppt

文档介绍

文档介绍:第九章
面向对象的编程
R语言是面向对象的语言,支持“封装”、“多态”、“继承”
封装:把独立但相关的数据项目打包为一个类的实例
多态:相同的函数使用不同类的对象时可以调用不同的操作;具有多态性的函数,成为泛型函数,如plot()和print()
继承:允许把一个给定的类的性质自动赋予为其下属的更特殊化的类
实例:lm()的面向对象的编程(OOP)
x<-c(1,2,3)
y<-c(1,3,8)
lmot<-lm(y~x)
class(lmot)
lmot #输入lmot就能将lmot的内容自动打印出来
Call:
lm(formula = y ~ x)
Coefficients:
(Intercept) x
-
#事实上,由于R的解释器发现lmot是lm类的对象,()
> (lmot)
Call:
lm(formula = y ~ x)
Coefficients:
(Intercept) x
-
去掉类属性,打印的结果将会有所不同
unclass(lmot)
$coefficients
(Intercept) x
-
$residuals
1 2 3
-
$effects
(Intercept) x
- -
$rank
[1] 2
$
1 2 3
4
………
显然,()的显示结果更加简练
编写S3类
j<-list(name="Joe",salary=55000,union=T)
> class(j)
[1] "list"
> class(j)<-"employee" #把j改为employee类
> attributes(j)
$names
[1] "name" "salary" "union"
$class
[1] "employee"
查看k的默认打印效果
j
$name
[1] "Joe"
$salary
[1] 55000
$union
[1] TRUE
attr(,"class")
[1] "employee"
自定义打印方法
<-function(wrkr){
cat(wrkr$name,"\n")
cat("salary",wrkr$salary,"\n")
cat("union member",wrkr$union,"\n")
}
methods(,"employee")
[1]
> j
Joe
salary 55000
union member TRUE
继承
kl<-list(name="Kate",salary=68000,union=F,hrsthismonth=2)
> class(kl)<-c("hrlyemployee")
> kl
$name
[1] "Kate"
$salary
[1] 68000
$union
[1] FALSE
$hrsthismonth
[1] 2
attr(,"class")
[1] "hrlyemployee"
k<-list(name="Kate",salary=68000,union=F,hrsthismonth=2)
> class(k)<-c("hrlyemployee","employee")
> k
Kate
salary 68000
union member FALSE
S4类
定义类:用setClass()函数
创建对象:用new()函数
setClass("employee",
representation(
name="character",
salary="numeric",
union="logical")
)
joe<-new("employee",name="Joe",salary=55000,union=T)
joe
An object of class "employee"
Slot "name":
[1] "Joe"
Slot "salary":
[1] 55000
Slot "union":
[1] TRUE
成员符号位slot,引用符号为@,也可以通过slot()函数查询对象
******@salary
[1] 55000
slot(joe,"salary")
[1] 55000
也可以重新赋值
******@salary<-60000
> joe
An object of class "employee"
Slot "name":
[1] "Joe"
Slot "salary