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

前端 未结 4 2136
别跟我提以往
别跟我提以往 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:14

    I had a similar requirement. I pulled all the elements I needed to a list:

    varsToPurge = as.list(ls())
    

    I then reassign the few values I wish to keep with new variable names which will not be in the variable varsToPurge. After that I looped through the elements

    for (j in 1:length(varsToPurge)){
      rm(list = as.character(varsToPurge[j]))
    }
    

    Do a little garbage collecting, and you maintain a clean environment as you go through your code.

    gc()
    

    You can also use a vector of row numbers you wish to keep instead and run through the vector in the loop but it won't be as dynamic if you add rough work you wish to remove.

提交回复
热议问题