文档详情

R语言-第九章.ppt

发布:2018-10-11约2.16千字共13页下载文档
文本预览下载声明
* 第九章 面向对象的编程 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 -3.0 3.5 #事实上,由于R的解释器发现lmot是lm类的对象,自动调用了print.lm() print.lm(lmot) Call: lm(formula = y ~ x) Coefficients: (Intercept) x -3.0 3.5 去掉类属性,打印的结果将会有所不同 unclass(lmot) $coefficients (Intercept) x -3.0 3.5 $residuals 1 2 3 0.5 -1.0 0.5 $effects (Intercept) x -6.928203 -4.949747 1.224745 $rank [1] 2 $fitted.values 1 2 3 0.5 4 ……… 显然,print.lm()的显示结果更加简练 编写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 自定义打印方法 print.employee-function(wrkr){ cat(wrkr$name,\n) cat(salary,wrkr$salary,\n) cat(union member,wrkr$union,\n) } methods(,employee) [1] print.employee 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()函数查询对象 joe@salary [1] 55000 slot(joe,salary) [1] 55000 也可以重新赋值 joe@salary-60000 joe An object of class employee Slot name
显示全部
相似文档