R语言S3和S4类

R语言的类有S3类和S4类,S3类用的比拟广,创立简单精细但是灵活,而S4类比较精细,具有跟C++一样严格的结构。S3和S4的一大区别就是S3通过$访问不同属性,而S4通过@访问。

### 1. S3类创建
##创建person,包含name,age,gender等三种属性
person<-list(name="xiao ming", age=16, gender="M")
person
person$name
class(person) <- append(class(person), "people") #添加类名“people”
class(person)
# install.packages("pryr")
library(pryr)
otype(person)

### 2. S4类创建
ExprSet <- setClass(
  Class = 'ExprSet',
  slots = c(
    data = 'matrix',
    meta.data = 'data.frame',
    samples = 'character',
    genes = 'character'
  )
)

##设置data的非负检查
setValidity("ExprSet",function(object) {
  if (any(object@data <= 0)) stop("Count data should be greater than 0.")
})

ScExprSet <- setClass(
  Class = 'scExprSet',
  contains="ExprSet" # 父类
)
## 查看
otype(ExprSet)
isS4(ExprSet)
isS4(ScExprSet)

## new实例化
exprSet_null <-new("ExprSet")
exprSet_null2<-initialize(exprSet_null,samples = c("s1","s2","s3"))
exprSet1 <-new("ExprSet",data=matrix(c(3:14), nrow = 4))
exprSet1 <-new("ExprSet",data=matrix(c(-1:10), nrow = 4)) # 报错,不能为负
scExprSet_null <-new("ScExprSet")

## 通过自定义函数实例化
CreateExprSetObject <- function(
    count = NULL,
    meta = NULL,
    samples = NULL,
    genes = NULL
    ) 
{  
  # 数据赋值,可以加入判断、计算等
  data = count
  meta.data = meta
  samples = samples
  genes = genes
  new.exprSet <- new(Class = 'ExprSet',data = data,
                     meta.data = meta.data,
                     samples = samples,
                     genes = genes)

  return(new.exprSet)
}
exprSet2 <- CreateExprSetObject(count=matrix(c(3:14), nrow = 4),
                                meta = data.frame(),
                                samples = c("s1","s2","s3","s4"),
                                genes =c(paste0("g",1:4)))

##访问S4对象的属性
exprSet2@data
slot(exprSet2, "samples")

### 3.S4 methods
## 创建泛型函数
setGeneric("logCount", function(object) standardGeneric("logCount"))
# 或(一般用于S3对象泛型函数的创建)
logCount <- function(object,...) {
  UseMethod(generic = 'logCount', object = object)
}

## 创建方法
setMethod(f="logCount", signature="ExprSet", definition = function(object)
  { return (log(object@data+1))})
# setMethod通常有3个参数:
# f: 泛型函数的名称、
# signature: 匹配该方法类签名
# definition: 具体函数功能

## 使用方法
log_count <- logCount(exprSet2)

##查看S4对象的函数
# 检查方法
ftype(logCount)
# 直接查看logCount函数
logCount
# 查看logCount函数的现实定义
showMethods(logCount)
# 查看ExprSet对象的logCount函数定义
getMethod("logCount", "ExprSet")
selectMethod("logCount", "ExprSet")
# 检查ExprSet对象有没有logCount函数
existsMethod("logCount", "ExprSet")
hasMethod("logCount", "ExprSet")

参考:

https://zhuanlan.zhihu.com/p/360584550?utm_id=0

https://blog.csdn.net/flashan_shensanceng/article/details/117291584

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值