热门IT资讯网

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

发表于:2024-11-24 作者:热门IT资讯网编辑
编辑最后更新 2024年11月24日,R语言中,简单的S3和S4类的定义# S3 classnewstudent <- function(sid, sname, ssex){tmp <- list(id = sid, name = sna

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


0