6 两种class: s3和s4

https://www.youtube.com/watch?v=YGlse2aW5Ao

6.1 s3

s3 <- list(name = "John", age = 21, GPA = 3.5)  # one list
class(s3) <- "student"  # s3 is now an object of class student
s3
## $name
## [1] "John"
## 
## $age
## [1] 21
## 
## $GPA
## [1] 3.5
## 
## attr(,"class")
## [1] "student"

另一种方法

s3.2 <- list(name = "John", age = 21, GPA = 3.5)
attr(s3.2, "class") <- "student"
s3.2$name  # 访问就是用普通的$
## [1] "John"

基本就是要先把元素塞进一个list,然后用一次class函数。如果要快速建某class的object只能自定义一个函数

anmelden <- function(n, a, g) {
    value <- list(name = n, age = a, GPA = g)
    class(value) <- "student"
    return(value)
}

hammerfly <- anmelden("hammerfly", 27, 3)
hammerfly
## $name
## [1] "hammerfly"
## 
## $age
## [1] 27
## 
## $GPA
## [1] 3
## 
## attr(,"class")
## [1] "student"

有了class就可以建造函数快速套到object上

grade <- function(miao) {
    cat("your grade is", miao$GPA)
}

grade(s3)
## your grade is 3.5

6.2 s4

s4得先定义class。注意必须得同时加slots,否则new时会出错。

setClass("student", slots = list(name = "character", age = "numeric", GPA = "numeric"))
setClass("student", slots = c(name = "character", age = "numeric", GPA = "numeric"))  # 不用list用向量也是一样
s4 <- new("student")
s4
## An object of class "student"
## Slot "name":
## character(0)
## 
## Slot "age":
## numeric(0)
## 
## Slot "GPA":
## numeric(0)
s4 <- new("student", name = "John", age = 21, GPA = 3.5)
s4
## An object of class "student"
## Slot "name":
## [1] "John"
## 
## Slot "age":
## [1] 21
## 
## Slot "GPA":
## [1] 3.5

判断对象是不是s4

isS4(s4)
## [1] TRUE
isS4(s3)
## [1] FALSE

@访问s4里的元素

s4@age
## [1] 21
s4@age <- 50
s4
## An object of class "student"
## Slot "name":
## [1] "John"
## 
## Slot "age":
## [1] 50
## 
## Slot "GPA":
## [1] 3.5

或者用slot,虽然我不明所以但似乎更推荐

slot(s4, "name")
## [1] "John"