Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading and removing datasets using paste in R

Tags:

r

paste

I have a large number of similarly named .R datasets. I am trying to load them in (which i can do successfully), do something to them and then remove them from the workspace all in one loop. I am struggling however to remove them because they are in the wrong class coming out of the paste command. While I know whats wrong, I have no idea how to correct my code, so suggestions are welcome. Here is some example code

for(i in 1:n){
    load(paste("C",i,".R",sep=""))
    # do stuff to dataset
    rm(paste("C",i,sep="")) #this line is clearly wrong
}

Thanks for the help

like image 938
Vinny Davies Avatar asked Mar 11 '23 16:03

Vinny Davies


1 Answers

The list argument of rm should do what you want. It takes character of variable names which are removed. So, something like this should work:

for (i in 1:n) {
  loaded <- load(paste0("C", i, ".R"))
  # do stuff to dataset
  rm(list = loaded)
}

Note, that the load function returns a character with the names of the loaded object(s). So we can use that when removing the loaded object(s) again. The loaded object(s) with load does not nessesarily correspond to the filename.

like image 86
Anders Ellern Bilgrau Avatar answered Mar 24 '23 14:03

Anders Ellern Bilgrau