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

前端 未结 3 460
暗喜
暗喜 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: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

提交回复
热议问题