How to find all attached data frames?

只谈情不闲聊 提交于 2019-11-28 10:05:20

问题


When I attach a data.frame in R studio, I get this message:

The following objects are masked from......

I forgot to detach the data.frame

data<-read.table(file.choose(),header=TRUE)
View(data)
attach(data) 
## The following objects are masked from vih (pos = 3):
## edad, edadg, id, numpares, numparg, sifprev, udvp, vih 
## The following objects are masked from vih (pos = 4):
## edad, edadg, id, numpares, numparg, sifprev, udvp, vihhere

Is there a way of knowing which data.frames are attached?

Is there a way of detaching ALL the data.frames with one command or function?


回答1:


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)))
}


来源:https://stackoverflow.com/questions/29706764/how-to-find-all-attached-data-frames

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!