Let's say I want to define two classes classes, Sentence
and Word
. Each word object has a character string and a part of speech (pos). Each sentence contains some number of words and has an additional slot for data.
The Word
class is straightforward to define.
wordSlots <- list(word = "character", pos = "character")
wordProto <- list(word = "", pos = "")
setClass("Word", slots = wordSlots, prototype = wordProto)
Word <- function(word, pos) new("Word", word=word, pos=pos)
Now I want to make a Sentence
class which can contain some Word
s and some numerical data.
If I define the Sentence
class as so:
sentenceSlots <- list(words = "Word", stats = "numeric")
sentenceProto <- list(words = Word(), stats = 0)
setClass("Sentence", slots = sentenceSlots, prototype = sentenceProto)
Then the sentence can contain only one word. I could obviously define it with many slots, one for each word, but then it will be limited in length.
However, if I define the Sentence
class like this:
sentenceSlots <- list(words = "list", stats = "numeric")
sentenceProto <- list(words = list(Word()), stats = 0)
setClass("Sentence", slots = sentenceSlots, prototype = sentenceProto)
it can contain as many words as I want, but the slot words
can contain objects which are not of the class Word
.
Is there a way to accomplish this? This would be similar to the C++ thing where you can have a vector of objects of the same type.