学而时习之,不亦说乎?
学到的东西有机会付诸实践,这难道不是一件值得高兴的事情吗?
我这就来记录一下自己学习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