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

前端 未结 4 2132
别跟我提以往
别跟我提以往 2021-01-05 07:41

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, bu

4条回答
  •  南笙
    南笙 (楼主)
    2021-01-05 08:24

    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.

提交回复
热议问题