Using default values ​​in a specific class in R

I am trying to define a class, one of its slots of which is a list. The definition of my class is as follows:

setClass("myClass",
     slots=c(a="matrix", 
             b="matrix", 
             c="character", 
             d="list"))

d - a list of some parameters as follows:

d <- list(d1=c('as','sd'), d2=c(2,3,4), d3=5)

The number of elements in dis variable, that is, in one object it can only have d1, and in another object it contains d1and d2.

I want to define an object like this:

myObject=new("myClass", 
       a = matrix(0, nrow=3, ncol=5), 
       b=matrix(1, nrow=2, ncol=3), 
       c='first', 
       d=list(d1=c('ak','fd','sd'), d2=c(2,3,4)))

After defining, myObjectI want to set the default value d3in the list d, but I do not know how to do it. I appreciate if anyone can help me.

Thank.

+4
source share
1 answer

The class can be equipped with a prototype.

.myClass <- setClass("myClass",
     slots=c(a="matrix", 
             b="matrix", 
             c="character", 
             d="list"),
     prototype=prototype(
             d=list(d1=c('as','sd'), d2=c(2,3,4), d3=5)))

, d,

d=list(d1=c('ak','fd','sd'), d2=c(2,3,4))
myd <- getClass("myClass")@prototype@d
myd[names(d)] <- d

.myClass(d=myd)

, initialize() , ,

myClass <- function(a, b, c, d, ...) {
    myd <- getClass("myClass")@prototype@d
    myd[names(d)] <- d
    .myClass(a=a, b=b, c=c, d=myd, ...)
}

, , ; , d1, d2, d3?

+2

All Articles