我有S4对象的列表。我需要检查,如果一个S4对象存在于该列表中。我曾尝试在本页面发现没有成功一些替代方案:
我试图与存在:
exists(foo,where=my_list)
Error in list2env(list(<S4 object of class "Atributo">, <S4 object of class "Atributo">,
;names(x) must be a character vector of the same length as x
随着比赛:
match(foo, my_list)
'match' requires vector arguments
比赛的二进制运算符的结果相同%的%:
foo %in% my_list
'match' requires vector arguments
和is.element:
is.element(foo,my_list)
Error in match(el, set, 0L) : 'match' requires vector arguments
例如我已经创建5个元素,并与其中只有3制成的列表。我需要知道,如果一个特定的元素列表:
setClass("foo", representation = representation(bar = "numeric"))
one <- new("foo", bar = 12)
two <- new("foo", bar = 13)
three <- new("foo", bar = 14)
four <- new("foo", bar = 15)
five <- new("foo", bar = 16)
mylist <- list(one,two,three)
我想,以检查是否在列表中,例如存在一个特定的元素:
usefull_function(four,my_list)
FALSE
usefull_function(two,my_list)
TRUE
我知道,如果他们是S4的元素,我可以检查是否在环境中的列表中存在的环境。 ¿如何会做一个优雅的/快速的方式?
谢谢。
sapply
,any
和is
的组合应该工作。
setClass("foo", representation = representation(bar = "numeric"))
baz <- new("foo", bar = 42)
mylist <- list("hello", baz, 13)
any(sapply(mylist, is, class2 = "foo"))
关于列表中的对象的名字,我只能想到的两种方法
构建列表时,添加名字
mylist <- list(one=one,two=two,three=three)
"one" %in% names(mylist)
比较对象元素
mylist <- list(one,two,three)
any(sapply(mylist, function(x) identical(one, x)))
[1] TRUE
any(sapply(mylist, function(x) identical(four, x)))
[1] FALSE
注意 - 此第二种方法假设对象中的元素都是不同的所以最好你可以使用第一方法。
我有同样的问题,但我认为你应该修改你的S4类定义
setClass("foo", representation = representation(bar = "numeric"))
至
setClass("foo", representation = representation(name='character',bar = "numeric"))
然后
one <- new("foo",name='one', bar = 12)
two <- new("foo", name='two', bar = 13)
three <- new("foo",name='three', bar = 14)
four <- new("foo", name='four',bar = 15)
five <- new("foo", name='five',bar = 16)
mylist <- list(one,two,three)
那么你可以设计功能苛求从对象中的所有名称和比较他们的名字