About Environment Data in Rstudio

If I just want to remove some objects in Rstudio Environment, not all subjects. Just use the function rm, like the code example? Is there any other methods and operation?
Any help would be appreciated.

Update: the object refers to the data in Rstudio Environment like the picture shows.

rm(list = ls()[match(c("rowcount"),ls())])

Created on 2023-06-01 with reprex v2.0.2

This kind of depends on your definition of an object.

The rm() function can remove variables and sourced functions, it will not detach packages loaded via library() call or reset environment variables.

It is not fully bulletproof and having rm(list = ls()) on top of every script (customary in the days of yore to ensure you were running your code from a clean slate), is nowadays considered bad manners.

On the other hand if you are running a complicated calculation with lots of intermediary steps on a memory constrained piece of hardware rm() can truly be your friend. I would suggest to use it only to remove a specific object listed by name; not the output of ls().

1 Like
foo <- mtcars
bar <- foo
baz <- bar
important <- vector()
crucial <- vector()
essential <- vector
(present <- ls())
#> [1] "bar"       "baz"       "crucial"   "essential" "foo"       "important"
discard <- c(1:2,5)
rm(list = present[discard])
(present <- ls())
#> [1] "crucial"   "discard"   "essential" "important" "present"

Thank you! From the example, I know that ls() would show all variables exist. And by a vector, we could remove specific variables. What's more, in the example code, after using the rm, present variable contains present. It because we run (present <- ls()) in seventh rows of code?

present just captures what's currently in namespace as shown by ls(). Looking at it allows spotting the index numbers of objects to be removed which is assigned to discard. Then present[discard] returns a list of object names to be given to rm() and the last ls() is just to show what is left.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.