Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
2 views
in R Programming by (5.3k points)
edited by

I have a workspace with lots of objects and I would like to remove all but one. Ideally, I would like to avoid having to type rm(obj.1, obj.2... obj.n). Is it possible to indicate remove all objects but these?

2 Answers

0 votes
by
edited by

To remove all objects but one from R workspace, use the setdiff function from the sets base R package.

The basic syntax for setdiff is given below:

setdiff(x, y)

x, y :-

Vectors (of the same mode) containing a sequence of items (conceptually) with no duplicate values.

For example:

The code below will remove all the objects in R workspace except “x”

x <- c("A","B","C","D")

y <- 2 z <- data.frame(name = "SAM", age = 22, gender = "Male") rm(list=setdiff(ls(), "x")) 

ls()

[1] "x"

If you want to explore more in R programming then watch this R programming tutorial for beginners:

0 votes
by (106k points)
edited by

To remove all objects in r you can use the 'keep()' function from the 'gdata' package:

library(gdata)

You can see that which objects will be removed:

>>>keep(num1)

"num2" "num3" "num4" "num5"

If you want to remove objects, you need to add sure=TRUE

>>>keep(num1,sure = TRUE)

>>>ls()

"num1"

Browse Categories

...