【问题标题】:Pulling all objects in the global environment that have specific attributes拉取全局环境中具有特定属性的所有对象
【发布时间】:2011-05-03 03:59:05
【问题描述】:

假设我有一个全局环境中的对象列表。我将如何只提取具有特定属性集的那些?

x1 <- 1:10
x2 <- 1:10
x3 <- 1:10
x4 <- 1:10
x5 <- 1:10 

attr(x1, "foo") <- "bar"
attr(x5, "foo") <- "bar"

如何根据 x1 和 x5 的属性“foo”作为“bar”来拉取它们?

【问题讨论】:

    标签: r


    【解决方案1】:

    Ramnath 回答的几个变体。

    为了获取多个对象,最好使用mget 而不是getlapply

    all <- mget(ls(), envir = globalenv())
    

    您可以使用Filter 过滤变量列表。我认为这使代码的意图更加清晰。 (虽然它在引擎盖下做同样的事情。)

    Filter(function(x) attr(x, "foo") == "bar", all)
    

    【讨论】:

      【解决方案2】:

      这是一种方法

      # collect all objects in global environment
      all = lapply(ls(), get)
      
      # extract objects with attribute = "bar"
      bar = all[lapply(all, attr, "foo") == "bar"]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-02
        • 1970-01-01
        • 2021-01-24
        • 2015-03-24
        • 1970-01-01
        • 2018-07-20
        • 2016-03-04
        • 2020-10-25
        相关资源
        最近更新 更多