证明 S4 对象是否相同

Kla*_*aus -5 r r-s4

我有两个包含S4对象的列表。现在我想询问 list_1 的元素是否包含 list_2 的元素,就像我在下面的字符向量列表示例中所做的那样。

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

但它能证明物体是否相同吗?如果不是,如何在不使用循环的情况下选择list_1中存在于list_2中的元素?

pla*_*pus 5

如果你想比较 S4 对象,我相信你将不得不使用(正如 Ben Bolker 建议的那样)函数slotNamesslot和 的混合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 
Run Code Online (Sandbox Code Playgroud)

现在,如果您想将其扩展到 S4 对象列表,请在 Metrics 解决方案之上使用:

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 
Run Code Online (Sandbox Code Playgroud)