The ls() code lists all of the objects in your workspace. The rm() code removes objects in your workspace. You can begin your code with the rm() function to clear all of the objects from your workspace to start with a clean environment.
We use rm() function to remove variables while the arguement "list = ls()" will make sure all of the variables are removed from the list. ls() gives the list of all the variables in the session. This would also remove functions assigned in the session.
(ls() %in% c('keepThis','andThis'))] will give the elements excluding 'keepThis' and 'andThis'. Thus rm(list= ls()[! (ls() %in% c('keepThis','andThis'))]) will remove everything except these two objects, and hidden objects. It you want to remove the hidden objects as be use ls(all=TRUE).
remove() Functions. Actually, there are two different functions that can be used for clearing specific data objects from the R workspace: rm() and remove().
Here's a one-liner that removes all objects except for functions:
rm(list = setdiff(ls(), lsf.str()))
It uses setdiff
to find the subset of objects in the global environment (as returned by ls()
) that don't have mode function
(as returned by lsf.str()
)
The posted setdiff
answer is nice. I just thought I'd post this related function I wrote a while back. Its usefulness is up to the reader :-).
lstype<-function(type='closure'){
inlist<-ls(.GlobalEnv)
if (type=='function') type <-'closure'
typelist<-sapply(sapply(inlist,get),typeof)
return(names(typelist[typelist==type]))
}
You can use the following command to clear out ALL variables. Be careful because it you cannot get your variables back.
rm(list=ls(all=TRUE))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With