Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

r - How to find all attached data frames?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...