-5

我有两个包含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

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

4

3 回答 3

4

如果您想比较 S4 对象,我相信您将不得不使用(如 Ben Bolker 建议的那样)混合函数slotNamesslotsapply.

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 

现在,如果您想将其扩展到 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 
于 2013-09-03T14:44:48.503 回答
2

您可以Map为此使用:

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

$b
[1]  TRUE FALSE FALSE

或者,正如@plannapus 所建议的,只需使用:

Map(`%in%`,s,t) 
于 2013-09-03T13:04:18.520 回答
-2

现在我定义了一个运算符,我是否以正确的方式执行此操作?

"%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
于 2013-09-03T15:07:54.653 回答