R - "list" for a list of custom classes

I have some custom classes, for example:

setClass("foo", slots = c(mat = "matrix")) 

I want to handle how the list of foo objects is not listed.

 mat <- matrix(rnorm(16), 4) foo <- new("foo", mat = mat) unlist(list(foo)) 

I thought I might have created methods for c (which I thought was used, but maybe wrong) and unlist would solve the problem.

S3 version

 #' @export unlist <- function(x, ...) UseMethod("unlist", x) #' @export unlist.default <- base::unlist #' @method unlist foo #' @export unlist.foo <- function(x, ...){ print("called foo unlist") } 

S4 version

 #' @export setMethod("unlist", signature = "foo", function(x, recursive = TRUE, use.names = TRUE){ print("call foo unlist") }) 

c Function

 #' @export setMethod("c", signature = "foo", function(x, ..., recursive = FALSE){ print("called foo c") }) 

But I only see a confirmation message when I use c directly:

 c(foo) [1] "called foo c" 

unlist just returns the same object without a print message

 unlist(list(foo)) [[1]] An object of class "foo" Slot "mat": [,1] [,2] [,3] [,4] [1,] 0.6711541 -0.2783441 -0.4707375 -0.23060105 [2,] 0.7408401 0.4076826 2.2757187 -0.48547413 [3,] 1.8640581 0.3610619 -0.4632473 -0.06498348 [4,] -0.5595930 0.6679157 -0.8142456 0.27499963 

If I call unlist(foo) , then I get a print message, but I need to apply it in the list of foo objects. Any thoughts on how I can have unlist handle custom classes in a list?

Ultimately, I want the following to return TRUE :

 all.equal(unlist(list(foo)), unlist(list(mat))) 
+6
source share
1 answer

I am afraid that this is impossible. unlist determines the type of its output based on the types of the individual list items it receives. If all elements are atomic, as in the case where the only element is foo (the matrix), he does something for his argument - he arranges the arguments for the general atomic vector (there is only one) and forgets most of its attributes (for example, measurements ) However, he does not consider S4 objects (for example, foo ) that are based on atomic vectors as atomic vectors: these S4 objects will therefore be left untouched as a result, and the result will have a list of types. So calling unlist on list(foo) returns list(foo) . The behavior is implemented in C ( do_unlist in bind.c ) and, it seems to me, is consistent with the documentation.

To mimic the desired behavior in a subset of the possible ways to use unlist , you could probably implement a new class for a list of foo objects, define list for foo , and then define a new unlist so that this list-of-foo class behaves just like The default behavior of the unlist C-list behaves in the list of atomic vectors (I have not tried).

0
source

All Articles