public
Created

Vectors of S4 classes with non-trivial slots

  • Download Gist
gistfile1.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
movie = c("Thunderball", "Goldfinger")
rating = c(4,5)
dfJoe = data.frame(movie = movie, rating = rating)
 
movie = c("Manhattan", "Interiors", "Radio Days", "Bananas")
rating = c(5, 4, 3, 5)
dfBob = data.frame(movie = movie, rating = rating)
 
setClass("BorrowedStuff", representation(stuff = "data.frame", from="character"))
 
JoesStuff = new("BorrowedStuff", from = "Joe", stuff = dfJoe)
 
BobsStuff = new("BorrowedStuff", from = "Bob", stuff = dfBob)
 
sillyFunction = function(x){
x + 1
}
 
sillyFunction(1)
sillyFunction(1:10)
 
whatStuff = new("BorrowedStuff", from = c("Joe", "Bob"), stuff = c(dfJoe, dfBob))
whatStuff = new("BorrowedStuff", from = c("Joe", "Bob"), stuff = list(dfJoe, dfBob))
 
setMethod("c", signature(x = "BorrowedStuff"), function(x, ...){
elements = list(x, ...)
stuffList = list()
for (i in 1:length(elements)){
stuffList[i] = new("BorrowedStuff", from = slot(elements[[i]], "from"), stuff = slot(elements[[i]], "stuff"))
}
class(stuffList) = "BorrowedStuff"
stuffList
})
 
whatStuff = c(JoesStuff, BobsStuff)
whatStuff[[1]]@stuff
 
someStuff = whatStuff[[1]]

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.