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

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
) ) )

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.


There is a much simpler and more direct solution:

vars.to.remove <- ls()
vars.to.remove <- temp[c(1,2,14:15)]
rm(list = vars.to.remove)

Or, better yet, if you are good about variable naming schemes, you can use the following pattern matching strategy:

E.g. I name all temporary variables with the starting string "Temp." ... so, you can have Temp.Names, Temp.Values, Temp.Whatever

The following produces the list of variables that match this pattern

ls(pattern = "^Temp\\.")

So, you can remove all unneeded variables using ONE line of code, as follows:

rm(list = ls(pattern = "^Temp\\."))

Hope this helps.

Tags:

Variables

R

Reset