Search code examples
rclassr-s4

How to initialize the new object in S4 class?


I have data as like the following:

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

I have defined a S4 class to read this data as longitudinalData. The class goes as follows.

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

To initiate a new object in this class I have defined the following function.

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

when I try add a new object by make_LD(data) I get the following error.

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

What does this error means?

How to get rid of this?


Solution

  • The easiest way to avoid these sorts of problems is to save the value from setClass, which returns a handy constructor function for you to use.

    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
      )
    }
    

    It is normal to give the constructor function the same name as the class, but you don't have to.