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

前端 未结 3 469
暗喜
暗喜 2021-02-06 13:24

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

相关标签:
3条回答
  • 2021-02-06 13:32

    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.

    0 讨论(0)
  • 2021-02-06 13:54

    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
    
    0 讨论(0)
  • 2021-02-06 13:56

    This should work.

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

    Breaking it down:

    1. mget(ls()) gets all the objects in the global environment
    2. !sapply(..., is.data.frame determines which is not a data.frame
    3. rm(list=ls()[..] removes only the objects that are not data.frames
    0 讨论(0)
提交回复
热议问题