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

前端 未结 3 468
暗喜
暗喜 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.

提交回复
热议问题