【发布时间】:2018-12-05 07:17:33
【问题描述】:
我使用rstan::stan() 开发了一些包。我创建了一个函数,其返回值是rstan::stan() 生成的S4 类对象。为了方便地访问估计或添加数据信息,我想创建一个新的 S4 类对象,它继承 rstan::stan() 的 S4 类,以便有新的插槽。
此外,新的 S4class 对象还可以用于rstan 中的任何函数,例如rstan::traceplot()。
fit <- rstan::stan( model_name=scr, data=data) # This is a fictitious code.
假设我们得到名为 fit 的 S4 (stanfit) 对象。
定义一个扩展类 stanfit
InheritedClass <- setClass("InheritedClass",
# New slots
representation(slotA="character",
slotB="character",
slotC="numeric"),
contains = "stanfit"
)
要创建继承类的 S4 对象使用现有的 S4 类对象,即fit,
所以我只需要为添加的新插槽输入值,即 slotA、slotB、slotC。
使用以下代码,我们可以将旧类的 S4 对象转换为继承类:
fit2 <- as(fit,"InheritedClass")
使用它我们可以像下面这样编辑槽:
fit2@slotA <- "aaaaaaaaaaaa"
【问题讨论】: