I'm writing an S3 class in R that is just an integer with some attributes attached to it. If x1 and x2 are objects of this class (call it "myclass"), then I would like c(x1, x2) to return a vector of myclass objects with the original class definition and attributes intact. However, the documented behavior of c() is to remove attributes, so it would seem that I need to write my own c.myclass() method. My question is, how can I do this?
An example of the problem:
myclass <- function(x, n) structure(x, class="myclass", n=n)
x1 <- myclass(1, 5)
x2 <- myclass(2, 6)
c(x1, x2)
[1] 1 2
Here the result is just a vector of items of class numeric, and the original n attribute is gone.
Looking at the code for various packages, I sometimes see code like the following, in which we need to preserve the class attribute but nothing else:
c.myclass <- function(..., recursive = F) {
structure(c(unlist(lapply(list(...), unclass))), class="myclass")
}
Unfortunately I also cannot get this to work. The result of calling c.myclass(x1, x2) is a vector where the vector itself has class "myclass" but where each item in the vector has class numeric; I really want each item in the vector to have class "myclass". In practice I will also need to upgrade this method to preserve other attributes as well (like the attribute "n" in myclass).