Floop
Floop

Reputation: 21

R - Can I delete objects from workspace with index number or condition?

I am searching for a possibility to delete objects from my workspace in R by index number.

So for example I`ve got the vectors "a, b, c" and now I want to delete b without using the name. Is is possible to delete objects with a condition or directly with the index number in the workspace?

Thank you!

Kind Regards

Upvotes: 1

Views: 87

Answers (1)

Spacedman
Spacedman

Reputation: 94162

Use remove with the list argument?

Empty workspace:

> ls()
character(0)

Make some things:

> a=1; b=2; c=3
> ls()
[1] "a" "b" "c"

Now to remove the second thing in the working list:

> remove(list=ls()[2])
> ls()
[1] "a" "c"

The list argument will let you remove anything by passing its name as a character string. Its an odd thing to do in a program but if you want to clean up a workspace then yeah. Suppose you have a load of objects called test_1 up to test_99999 (illustrated with 4 here):

> ls()
[1] "keep_1" "test_1" "test_2" "test_3" "test_4"
> remove(list = ls()[grepl("^test_",ls())])
> ls()
[1] "keep_1"
> 

Upvotes: 1

Related Questions