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.
words="vector"
andx <- new("Sentence")
,x@words <- c(Word(),Word(),3)
causes no error and makesx@words
a list. – Kirchnerdata.frame(word=x,pos=y)
suffice? – BaulkParagraph
class which contained a variable number of sentences. I don't think data.frame would play nicely with that. (Also, some slots are things like length-20 logicals, which I'd rather have collected than taking up 20 rows of a data.frame) – Kirchnerwords
because it wasn't really a vector. Also,x@words <- c(Word(),Word())
still has x@words as a list even though the class definition has it as a vector. – KirchnerSentence
constructor. See, as an example of this, thePolygons
constructor of thesp
package. Then you can redifine the@<-
operators to avoid that the user set theword
slot bypassing your constraints. – Chaunce