【问题标题】:Removing objects in R environment that do not fit a criteria删除 R 环境中不符合条件的对象
【发布时间】:2017-07-13 01:02:43
【问题描述】:

我运行了一个循环,它遍历并创建了一堆对象,它们的名称都以“results_”开头,并且具有不同的nrow 长度,其中许多是 0。

为了使这个对象列表更易于处理,我想删除 nrow 等于 0 的所有对象。我尝试了以下针对与此类似的问题提供的各种解决方案,但没有一个有效对于我的特殊情况。我做错了什么?

Attempt 1: rm(list=ls(all=TRUE)[sapply(mget(ls(all=TRUE)), function(x) nrow(x) == 0)])

Attempt 2: rm(list=ls()[!sapply(mget(ls(),.GlobalEnv), function(x) { nrow(x) == 0 } )])

Attempt 3:

rm(list=
    Filter(
        Negate(is.na),                                  # filter entries corresponding to objects that don't meet function criteria   
        sapply(
            ls(pattern="^results_"),                     # only objects that start with "results_"
            function(x) if(nrow(x) == 0) x else NA   # return names of objects of nrow length 0
        )))

【问题讨论】:

  • 试试rm(list = ls(pattern = "results_")[sapply(ls(pattern = "results_"), function(x) NROW(get(x))) == 0])
  • @d.b 谢谢你的工作!如果您将其作为答案提交,我会检查它。另外,我不清楚为什么NROW 有效而nrow 无效。
  • 这是一个典型的x/y problem:真正的问题是你一开始就不应该创建这样的元素!相反,将数据组织在列表和 data.frames 中。

标签: r


【解决方案1】:

我会选择get,因为它返回对象而不是将其放入列表中。试试

rm(list = ls(pattern = "results_")[sapply(ls(pattern = "results_"), function(x)
                                                                    NROW(get(x))) == 0])

示例

results_1 = data.frame(x = 1:5)
results_2 = data.frame(x = numeric(0))
NROW(results_1)
#[1] 5
NROW(results_2)
#[1] 0
ls()
#[1] "results_1" "results_2"
rm(list = ls(pattern = "results_")[sapply(ls(pattern = "results_"), function(x)
                                                                    NROW(get(x))) == 0])
ls()
#[1] "results_1"

【讨论】:

  • 你知道为什么它需要NROW而不是nrow吗?我不清楚将向量视为 1 列矩阵有何影响。
  • @Phil, NROW 即使有向量也可以工作。试试NROW(1)nrow(1)
【解决方案2】:

关于您的问题,我的建议是将您的所有对象存储在一个列表中,然后在此列表中挖掘 nrow == 0 的对象。这比尝试使用变量名容易得多,因为 ls() 函数仅返回名称作为字符而不是对象本身,因此您需要找到一种方法来调用它们。下面我发布了一个简短的玩具示例,说明如何使用第一个矩阵为 nrow == 0 的列表来做到这一点。希望这会对您有所帮助。 最好的问候,


superList=c() #define a list to store your objects
for(i in 0:5){ #generate them and store them in your list, the first matrix has nrow = 0
  item=matrix(nrow = i,ncol=2)
  superList[[i+1]]=item
  print(i)

}
toErase=sapply(superList,function(x) nrow(x)==0)  #scan your list to find object with nrow==0
superList=superList[-which(toErase==TRUE)] #remove them from your list
sapply(superList,function(x) nrow(x)) #check that the first matrix

【讨论】:

    猜你喜欢
    • 2017-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多