How to find all attached data frames?

删除回忆录丶 提交于 2019-11-29 15:33:33

First, I suggest you stop using attach(). It's really a bad practice since there are almost always better alternatives (with() or data= parameters for example)

But you can see attached objects with

search()

If you assume all your data.frame names don't start with a "." and don't contain a ":", you could detach them all with

detach_dfs1 <- function() {
    dfs <- grep("^\\.|.*[:].*|Autoloads", search(), invert=T)
    if(length(dfs)) invisible(sapply(dfs, function(x) detach(pos=x)))
}

or if you assume that the data.frames are in the global environment, you could do

detach_dfs2 <- function() {
    dfs <- Filter(function(x) exists(x) && is.data.frame(get(x)), search())
    if(length(dfs)) invisible(sapply(dfs, function(x) detach(x, character.only=T)))
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!