Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: What does `rm(list=ls())` do? [duplicate]

Tags:

r

While looking at some R code written by someone else, I find near the top of the document rm(list=ls()). I tried looking up what the rm function does and as far as I can tell it deletes specified variables from the workspace, so that if you had x=3 somewhere, then after running rm(x) the variable x would behave as if it had never been assigned (so for instance would throw an error if you tried to print it).

But then the rest of the code is strange if I have this right, because it seems to be removing the empty list. So it's not doing anything at all, right? Is there a reason to have this code here?

like image 452
Addem Avatar asked Jan 28 '23 17:01

Addem


2 Answers

I think the parameter list for the rm function is confusing, at least it was for me when I started using R. The list parameter is not actually supposed to be a list but rather a character vector. The ls-function does return a character vector of all the named objects visible in the environment where it is called and it has a default value that gets used if no other value is offered for its envir argument. If you do this at the console, then the default environment is the global environment. So this will clear all the "visible" objects (but not the ones defined in other namespaces or environments like the ones that exist in the base, graphics, stats or other loaded package-namespaces.

So now go look at ?ls and ?rm to better understand their capabilities. In particular new useRs should get their heads clear on the differences between R names, i.e. symbols, versus the character representations of them. The ls function is really reaching into the language level of R's implementation and returning a non-language-level value, whereas rm typically takes a language level input ... unless (as in this case) it is offered a value to its "list"-argument, ... which is not an R list. Clear? Maybe, hopefully, a bit more so.

like image 200
IRTFM Avatar answered Feb 03 '23 06:02

IRTFM


It clears all objects from the workspace.

like image 34
RHertel Avatar answered Feb 03 '23 06:02

RHertel