R语言S3、S4方法的定义以及实例化

学而时习之,不亦说乎?

学到的东西有机会付诸实践,这难道不是一件值得高兴的事情吗?

我这就来记录一下自己学习R语言的一些心得,首先是其S3、S4类型的内容。

接下来,我将分别通过S3、S4创建一个名为Person的类,并将这个类加入到print这个泛型方法中去,最后在定义一个只属于Person这个类的方法。

#S3 method 
# define the S3
Person <- function(name, age, sex) {
  person <- list()
  person$name <- name
  person$age <- age
  person$sex <- sex
  class(person) <- "Person"
  person
}

# add the generic mtehod to the S3 class
print.Person <- function(x) {
  cat("The person is:", x$name, "\n")
  cat("The person's age is:", x$age, "\n")
  cat("The person's sex is:", x$sex, "\n")
}

# define the S3 own method
setAge <- function(x, age) UseMethod("setAge")

setAge <- function(x, age) {
  x$age <- age
  # x is a local variable, we must return 
  x
}



# 实例化S3
Bil
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值