Proof if S4 objects are identical

368 Views Asked by At

I have two lists that contain S4 objects. Now I want to ask if an element of list_1 contains an element of list_2, like I do in the following example for lists of character vectors.

s<-list(a=LETTERS[1:3],b=LETTERS[4:6])
t<-list(n=LETTERS[1:3],v=LETTERS[1:4])
s %in% t

But does it prove if the objects are identical? If not, how to select the element of list_1 which exists in list_2 without using a loop?

3

There are 3 best solutions below

1
On

If you want to compare S4 objects I believe you will have to use (as Ben Bolker suggested) a mixture of functions slotNames, slot, and sapply.

setClass("MyClass",representation(Slot1="vector",Slot2="vector"))
x <- new("MyClass")
x@Slot1 <- 1:4
x@Slot2 <- LETTERS[1:4]
y <- new("MyClass")
y@Slot1 <- 1:4
y@Slot2 <- LETTERS[4:6]

id <- function(a,b){
        sapply(slotNames(a),function(x)identical(slot(a,x),slot(b,x)))
        }

id(x,y)
Slot1 Slot2 
 TRUE FALSE 

And now if you want to extend that to a list of S4 objects, use on top of that Metrics solution:

X <- new("MyClass")
X@Slot1 <- 1:5
X@Slot2 <- LETTERS[1:4]
Y <- new("MyClass")
Y@Slot1 <- 1:4
Y@Slot2 <- letters[1:4]

a <- list(l1 = x, l2 = X)
b <- list(l1 = y, l2 = Y)

Map(id, a, b)
$l1
Slot1 Slot2 
 TRUE FALSE 

$l2
Slot1 Slot2 
FALSE FALSE 
4
On

You can use Map for that:

Map(function (x,y) x %in% y, s, t)
$a
[1] TRUE TRUE TRUE

$b
[1]  TRUE FALSE FALSE

Or, as suggested by @plannapus just use:

Map(`%in%`,s,t) 
1
On

Now I define a operator, did I do this in the right way?

"%inS4%" <- function(a,b) sapply(a,function(x) any(unlist(Map(identical,list(x),b))))
setClass(Class = "MyClass",
         representation = representation(name = "character",
                                         type = "character"
         )
)

a<-list(new("MyClass",name="abc",type="abc"),new("MyClass",name="abc",type="123"))
b<-list(new("MyClass",name="abc",type="123"),new("MyClass",name="abc",type="123"))

a %inS4% b