码迷,mamicode.com
首页 > 编程语言 > 详细

R语言中,简单的S3和S4类的定义

时间:2016-09-23 15:10:29      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:r   class   s3   s4   

R语言中,简单的S3和S4类的定义


# S3 class

newstudent <- function(sid, sname, ssex){

  tmp <- list(id = sid, name = sname, sex = ssex)

  class(tmp) <- "student"

  return(tmp)

}

print.student <- function(st){

  cat(st$id, "\n")

  cat(st$name, "\n")

  cat(st$sex, "\n")

}

st = newstudent(11, "jack", "male")

#print(st)

st

# S4 class

setClass("student",

         representation(

           id = "numeric",

           name = "character",

           sex = "character"

         ))

# print is not a S4 generic. show methods are mapped to print for convenience, though. 

setMethod("show", "student",

          function(object){

            cat(object@id, "\n")

            cat(object@name, "\n")

            cat(object@sex, "\n")

          })

st = new("student", id = 41, name = "tom",  sex = "male")

#print(st)

st


本文出自 “GONE WITH THE WIND” 博客,请务必保留此出处http://h2appy.blog.51cto.com/609721/1855788

R语言中,简单的S3和S4类的定义

标签:r   class   s3   s4   

原文地址:http://h2appy.blog.51cto.com/609721/1855788

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!