Assad Ebrahim Assad Ebrahim - 1 year ago 61
R Question

How to remove selected R variables without having to type their names

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.

Is there a way to remove several dozen manually selected variables from the workspace without having to:
a) clobber the entire workspace, e.g.

, or b) type each variable name, e.g.
remove(name1, name2, ...)

Ideal solution would be to use
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...)

Answer Source

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

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

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.

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download