I read in a public-use dataset that created dozens of temporary vectors in the process of building a final dataframe. Since this dataframe will be analyzed as part of a larger p
As an alternative approach (similar to @Ken's suggestion from the comments), the following code allows you to delete all objects created after a certain point, except one (or more) that you specify:
freeze <- ls() # all objects created after here will be deleted
var <- letters
for (i in var) {
assign(i, runif(1))
}
df <- data.frame(x1 = a, x2 = b, x3 = c)
rm(list = setdiff(ls(), c(freeze, "df"))) #delete old objects except df
The workhorse here is setdiff(), which will return a list a list of the items that appear in the first list but not the second. In this case, all items created after freeze except df. As an added bonus, freeze is deleted here as well.
I have scripts like this save the result as an RDS file and then open the result in a new session (or alternatively, after clearing everything). That is,
a <- 1
saveRDS(a, file="a.RDS")
rm(list=ls())
a <- readRDS("a.RDS")
a
## [1] 1
This should work.
source(file="script1.R")
rm(list=ls()[!sapply(mget(ls(),.GlobalEnv), is.data.frame)])
Breaking it down:
mget(ls()) gets all the objects in the global environment!sapply(..., is.data.frame determines which is not a data.framerm(list=ls()[..] removes only the objects that are not data.frames