【问题标题】:Exists S4 class element in a list列表中存在 S4 类元素
【发布时间】:2016-05-27 22:18:38
【问题描述】:

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

match的二元运算符给出相同的结果%in%:

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 元素,我可以检查环境是否存在于环境列表中。 ¿ 怎样才能优雅/快速地做到这一点?

谢谢。

【问题讨论】:

    标签: r list find exists s4


    【解决方案1】:

    sapplyanyis 的组合应该可以工作。

    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
    

    注意 - 第二种方法假定对象中的元素是不同的,因此最好使用第一种方法。

    【讨论】:

    • 该实现的问题是列表中总是有“foo”类对象。例如我有一个“baz”和一个“baz2”,需要检查是否存在“baz”而不是“baz2”
    • @FelipeGonzalez,哦,所以您正在寻找对象名称而不是类?还是两者兼而有之?
    • 名字并不重要。例如,我有 10 个“foo”类元素,而列表中只有 5 个,我需要检查一个元素是否在列表中。如何声明它的确切名称并不重要。
    • @FelipeGonzalez 也许你可以在你的问题中详细说明并证明这会失败。您是否要检查一个对象是否也在列表中?例如baz 存在且baz 也在mylist 中?
    • 我试图更好地解释。 any, sapply 和 is 的实际解决方案总是 TRUE
    【解决方案2】:

    我只是有同样的问题,但我认为你应该修改你的 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)
    

    然后你可以设计函数来从对象中提取所有名称并比较它们的名称

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-28
      • 2011-08-17
      • 2019-01-20
      • 2016-02-06
      • 2021-12-03
      • 1970-01-01
      • 2016-10-03
      相关资源
      最近更新 更多