R语言中s4对象的使用

下面是一个计算面积和周长的例子:

      # 实例化一个Square对象
        > s1<-new("Square",name="s1",edges=2)
        
        # 调用基类的getShape()函数
        > getShape(r1)
        Rectangle
        下面是完整的R语言的代码实现:
        
        
        setClass("Shape",slots=list(name="character",shape="ch

aracter"))
    setClass("Ellipse",contains="Shape",slots=list(radius="numeric"),prototype=list(radius=c(1,1),shape="Ellipse"))
    setClass("Circle",contains="Ellipse",slots=list(radius="numeric"),prototype=list(radius = 1,shape="Circle"))
    setClass("Rectangle",contains="Shape",slots=list(edges="numeric"),prototype=list(edges=c(1,1),shape="Rectangle"))
    setClass("Square",contains="Rectangle",slots=list(edges="numeric"),prototype=list(edges=1,shape="Square"))
    
    setGeneric("getShape",function(obj,...) standardGeneric("getShape"))
    setMethod("getShape","Shape",function(obj,...){
      cat(obj@shape,"\n")
    })
    
    
    setGeneric("area",function(obj,...) standardGeneric("area"))
    setMethod("area","Ellipse",function(obj,...){
      cat("Ellipse Area :\n")
      pi * prod(obj@radius)
    })
    setMethod("area","Circle",function(obj,...){
      cat("Circle Area :\n")
      pi*obj@radius^2
    })
    setMethod("area","Rectangle",function(obj,...){
      cat("Rectangle Area :\n")
      prod(obj@edges)
    })
    setMethod("area","Square",function(obj,...){
      cat("Square Area :\n")
      obj@edges^2
    })
    
    
    setGeneric("circum",function(obj,...) standardGeneric("circum"))
    setMethod("circum","Ellipse",function(obj,...){
      cat("Ellipse Circum :\n")
      2*pi*sqrt((obj@radius[1]^2+obj@radius[2]^2)/2)
    })
    setMethod("circum","Circle",function(obj,...){
      cat("Circle Circum :\n")
      2*pi*obj@radius
    })
    setMethod("circum","Rectangle",function(obj,...){
      cat("Rectangle Circum :\n")
      2*sum(obj@edges)
    })
    setMethod("circum","Square",function(obj,...){
      cat("Square Circum :\n")
      4*obj@edges
    })
    
    e1<-new("Ellipse",name="e1",radius=c(2,5))
    c1<-new("Circle",name="c1",radius=2)
    
    r1<-new("Rectangle",name="r1",edges=c(2,5))
    s1<-new("Square",name="s1",edges=2)
    
    area(e1)
    area(c1)
    circum(e1)
    circum(c1)
    
    area(r1)
    area(s1)
    circum(r1)
    circum(s1)

http://blog.fens.me/r-class-s4/

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值