+1 vote
1 view
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 ones?

2 Answers

0 votes
by (25.3k points)
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")) 


[1] "x"

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

0 votes
by (107k points)

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


You can see that which objects will be removed:


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

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

>>>keep(num1,sure = TRUE)



Welcome to Intellipaat Community. Get your technical queries answered by top developers !