如何在S4类中初始化新对象?

时间:2018-05-29 08:17:59

标签: r class s4

我的数据如下:

data = data.frame( id = rbinom(1000, 10, .75),
            visit = sample(1:3, 1000, replace = TRUE),
            room = sample(letters[1:5], 1000, replace = TRUE),
            value = rnorm(1000, 50, 10),
            timepoint = abs(rnorm(1000))
)
head(data)
id visit room    value  timepoint
1  8     3    a 62.53394 1.64681140
2  9     1    c 53.67313 1.04093204
3  6     1    c 64.96674 0.40599449
4  8     2    d 41.04145 0.09911475
5  7     2    b 63.86938 1.01732424
6  7     3    c 42.03524 2.04128413

我已经定义了一个S4类来将此数据读作longitudinalData。课程如下。

setClass("longitudinalData",
         slots = list(id = "integer", 
                      visit = "integer",
                      room = "character",
                      value = "numeric",
                      timepoint = 'numeric'))

要在此类中启动新对象,我已定义以下函数。

make_LD = function(x){
new("longitudinalData",
          id = x$id,
          visit = x$visit,
          room = x$room,
          value = x$value,
          timepoint = x$timepoint
  )
}

当我尝试按make_LD(data)添加新对象时出现以下错误。

> make_LD(data)
Error in initialize(value, ...) : 
  no slot of name "refMethods" for this object of class "classRepresentation"

这个错误意味着什么?

如何摆脱这个?

1 个答案:

答案 0 :(得分:1)

避免这些问题的最简单方法是保存setClass的值,它会返回一个方便的构造函数供您使用。

setClass("longitudinalData",
         slots = list(id = "integer", 
                      visit = "integer",
                      room = "character",
                      value = "numeric",
                      timepoint = 'numeric')) -> longitudinalData

make_LD = function(x){
longitudinalData(
          id = x$id,
          visit = x$visit,
          room = x$room,
          value = x$value,
          timepoint = x$timepoint
  )
}

给构造函数提供与类相同的名称是正常的,但是你不必这样做。