Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically remove a loaded object in R when object name is unknown?

Tags:

r

I have the problem where I need to load an object of file type .Rdata where the name of the object is unknown. I'm able to get the name by using verbose = TRUE in the load function. I then rename the object with get in order to standardize the object name for further processing steps. Now I would like to remove the original object by calling this name. I can't seem to get rm to address the character string held within my object that recorded the name:

a <- 1:10 # original data 'a'

z <- tempfile()
save(a, file=z) # saved to tempfile that doesn't contain the object name
rm(a) # then removed

obj.name <- load(z, verbose = TRUE) # 'a' is loaded and name recorded
b <- get(obj.name) # object is passed to 2nd object 'b' to standardize name

rm(list(get(obj.name))) # can't remove 'a' this way
# Error in rm(list(get(obj.name))) : 
#   ... must contain names or character strings

file.remove(z) # cleanup
like image 221
Marc in the box Avatar asked Jul 07 '16 14:07

Marc in the box


1 Answers

Just use rm(list = obj.name) as list accepts characters.

like image 169
Julius Vainora Avatar answered Sep 26 '22 03:09

Julius Vainora