I am trying to find a way to clear the workspace in R using lists.
According to the documentation, I could simply create a vector with all my workspace objects: WS=c(ls())
. But nothing happens when I try element wise deletion with rm(c(ls())
or rm(WS)
.
I know I can use the command rm(list=ls())
. I am just trying to figure how R works. Where did I err in my thinking in applying the rm()
function on a vector with the list of the objects?
Specifically, I'm trying to create a function similar to the clc
function in MATLAB, but I am having trouble getting it to work. Here's the function that I've written:
clc <- function() { rm(list = ls()) }
From ?rm
, "Details" section:
Earlier versions of R incorrectly claimed that supplying a character vector in ... removed the objects named in the character vector, but it removed the character vector. Use the list argument to specify objects via a character vector.
Your attempt should have been:
rm(list = WS)
HOWEVER, this will still leave you with an object (a character vector) named "WS" in your workspace since that was created after you called WS <- c(ls())
. To actually get rid of the "WS" object, you would have had to use rm(WS, list = WS)
. :-)
How does it work? If you look at the code for rm
, the first few lines of the function captures any individual objects that have been specified, whether quoted or unquoted. Towards the end of the function, you will find the line list <- .Primitive("c")(list, names)
which basically creates a character vector of all of the objects individually named and any objects in the character vector supplied to the "list" argument.
Based on your comment, it sounds like you're trying to write a function like:
.clc <- function() {
rm(list = ls(.GlobalEnv), envir = .GlobalEnv)
}
I think it's a little bit of a dangerous function, but let's test it out:
ls()
# character(0)
for (i in 1:5) assign(letters[i], i)
ls()
# [1] "a" "b" "c" "d" "e" "i"
.clc()
ls()
# character(0)
Note: FYI, I've named the function .clc
(with a dot) so that it doesn't get removed when the function is run. If you wanted to write a version of the function without the .
, you would probably do better to put the function in a package and load that at startup to have the function available.
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