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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With