How do I clear only a few specific objects from the workspace?

前端 未结 10 1746
陌清茗
陌清茗 2020-12-04 05:53

I would like to remove some data from the workspace. I know the \"Clear All\" button will remove all data. However, I would like to remove just certain data.

For exa

相关标签:
10条回答
  • 2020-12-04 06:11

    Use the following command

    remove(list=c("data_1", "data_2", "data_3"))
    
    0 讨论(0)
  • 2020-12-04 06:12

    A useful way to remove a whole set of named-alike objects:

    rm(list = ls()[grep("^tmp", ls())])
    

    thereby removing all objects whose name begins with the string "tmp".

    Edit: Following Gsee's comment, making use of the pattern argument:

    rm(list = ls(pattern = "^tmp"))
    

    Edit: Answering Rafael comment, one way to retain only a subset of objects is to name the data you want to retain with a specific pattern. For example if you wanted to remove all objects whose name do not start with paper you would issue the following command:

    rm(list = grep("^paper", ls(), value = TRUE, invert = TRUE))
    
    0 讨论(0)
  • 2020-12-04 06:14

    You'll find the answer by typing ?rm

    rm(data_1, data_2, data_3)
    
    0 讨论(0)
  • 2020-12-04 06:21

    If you're using RStudio, please consider never using the rm(list = ls()) approach!* Instead, you should build your workflow around frequently employing the Ctrl+Shift+F10 shortcut to restart your R session. This is the fastest way to both nuke the current set of user-defined variables AND to clear loaded packages, devices, etc. The reproducibility of your work will increase markedly by adopting this habit.

    See this excellent thread on Rstudio community for (h/t @kierisi) for a more thorough discussion (the main gist is captured by what I've stated already).

    I must admit my own first few years of R coding featured script after script starting with the rm "trick" -- I'm writing this answer as advice to anyone else who may be starting out their R careers.

    *of course there are legitimate uses for this -- much like attach -- but beginning users will be much better served (IMO) crossing that bridge at a later date.

    0 讨论(0)
  • 2020-12-04 06:23

    Following command will do

    rm(list=ls(all=TRUE))
    
    0 讨论(0)
  • 2020-12-04 06:25

    You can use the apropos function which is used to find the objects using partial name.

    rm(list = apropos("data_"))
    
    0 讨论(0)
提交回复
热议问题