如何删除选定的 R 变量而无需键入其名称 [英] How to remove selected R variables without having to type their names

查看:22
本文介绍了如何删除选定的 R 变量而无需键入其名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用随机生成的输入数据在 R 中测试模拟时,我发现并修复了一些错误,现在想使用相同的数据重新运行模拟,但删除所有中间变量以确保它是一个干净的测试.

While testing a simulation in R using randomly generated input data, I have found and fixed a few bugs and would now like to re-run the simulation with the same data, but with all intermediate variables removed to ensure it's a clean test.

有没有办法从工作区中删除几十个手动选择的变量,而不必:a) 破坏整个工作区,例如rm(list=ls()), 或 b) 输入每个变量名,例如remove(name1, name2, ...)?

Is there a way to remove several dozen manually selected variables from the workspace without having to: a) clobber the entire workspace, e.g. rm(list=ls()), or b) type each variable name, e.g. remove(name1, name2, ...)?

理想的解决方案是使用 ls() 来检查定义,然后挑选出我想要删除的索引,例如

Ideal solution would be to use ls() to inspect the definitions and then pick out the indices of the ones I want to remove, e.g.

ls()                        # inspect definitions
delme <- c(3,5,7:9,11,13)   # names selected for removal
remove(ls()[delme])         # DESIRED SOLUTION -- doesn't quite work this way

(事后看来,我应该使用固定种子来生成随机输入数据,这允许清除所有内容然后重新运行测试...)

(In hindsight, I should have used a fixed seed to generate the random input data, which allow clearing everything and then re-running the test...)

推荐答案

Assad,虽然我认为问题的实际答案在评论中,但让我建议将此模式作为更广泛的解决方案:

Assad, while I think the actual answer to the question is in the comments, let me suggest this pattern as a broader solution:

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

在这种情况下,我将删除所有以a"开头的矩阵对象.通过在此处修改 pattern 参数和 sapply 使用的函数,您可以很好地控制要删除的内容,而无需指定许多名称.

In this case, I'm removing all matrix object that start with "a". By modifying the pattern argument and the function used by sapply here, you can get pretty fine control over what you delete, without having to specify many names.

如果您担心这会删除您不想删除的内容,您可以将 Filter(... 操作的结果存储在一个变量中,查看内容,然后执行 rm(list=...) 命令.

If you are concerned that this could delete something you don't want to delete, you can store the result of the Filter(... operation in a variable, review the contents, and then execute the rm(list=...) command.

这篇关于如何删除选定的 R 变量而无需键入其名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆