Reputation: 469
I am trying to define class which one of its slots is a list. The definition of my class is as follows:
setClass("myClass",
slots=c(a="matrix",
b="matrix",
c="character",
d="list"))
d
is 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 d
is variable, i.e. in one object it may has just d1
and in another object it contains d1
and 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 myObject
, I want to set d3
in list d
to its default value, but I do not know how can I do that. I appreciate if anyone can help me.
Thanks.
Upvotes: 4
Views: 194
Reputation: 46856
A class can be provided 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)))
Code to use the prototype as a template updated by a variable d
might be
d=list(d1=c('ak','fd','sd'), d2=c(2,3,4))
myd <- getClass("myClass")@prototype@d
myd[names(d)] <- d
The new class could be instantiated with
.myClass(d=myd)
One could expose this in a more user-friendly way by defining an initialize()
method, or by writing a constructor, as
myClass <- function(a, b, c, d, ...) {
myd <- getClass("myClass")@prototype@d
myd[names(d)] <- d
.myClass(a=a, b=b, c=c, d=myd, ...)
}
Having a list as a slot kind of defeats the purpose of using classes in the first place; maybe it's better to have explicit slots d1, d2, d3?
Upvotes: 2