Cleaning up the global environment after searching: how to remove objects of a certain type in R

I read in a public data set that created dozens of time vectors in the process of constructing the final data block. Since this data block will be analyzed as part of a larger process, I plan sourceto create an R script that creates a data framework but does not want to leave me or future users with a cluttered global environment.

I know what I can use lsto display current objects in my global environment and use rmto delete certain objects, but I'm not sure how to use these two functions in agreement to delete all objects except the data frame created by a specific script .

To clarify, here is a reproducible example:

Script 1 called "script1.R"

setwd("C:/R/project")
set.seed(12345)
var <- letters
for (i in var) {
  assign(i, runif(1))
}
df <- data.frame(x1 = a, x2 = b, x3 = c)

Script 2

source("script1.r")

It would be easy enough to remove all the vectors of sourced script using some combination rm, lswith pattern = lettersor something like that, but I want to create a generic function that removes all of the vectors created by a particular script, and saves only data frame (in this example df).

( NOTE : there are similar questions, such as here and here , but I feel that mine differs from the fact that it is more specific for searching and cleaning in the context of a multi-script project).

Update Looking around, the following link gave me a good job:

R ?

, @Fojtasek :

, , , (), , . , , , .

, dataframe :

temp <- new.env()
with(temp, {
    var <- letters
for (i in var) {
  assign(i, runif(1))
}
df <- data.frame(x1 = a, x2 = b, x3 = c)
}

... (df) , , .

.

+4
3

( @Ken ) , , ( ), :

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

setdiff(), , , . freeze df. freeze.

+4

.

source(file="script1.R")
rm(list=ls()[!sapply(mget(ls(),.GlobalEnv), is.data.frame)])

:

  • mget(ls())
  • !sapply(..., is.data.frame , data.frame
  • rm(list=ls()[..] , data.frames
+3

I have scripts that save the result as an RDS file and then open the result in a new session (or, alternatively, after clearing everything). I.e

a <- 1
saveRDS(a, file="a.RDS")
rm(list=ls())
a <- readRDS("a.RDS")
a
## [1] 1
+1
source

All Articles