rm(list = ls())不会完全清除工作区

这是一个非常小的问题,但我想明确地知道这里发生了什么。

假设我执行以下操作:

library(RMySQL)
con <- dbConnect(MySQL(), host="some.server.us-east-1.rds.amazonaws.com",user="aUser", password="password", dbname="mydb")

values1 <- dbGetQuery(con,"select x,y from table1")
attach(values1)

在这一点上,我可以做到

rm(list=ls())

values2 <- dbGetQuery("select x,y from table1")
attach(values2)

但附件给了我一个关于屏蔽x和y的警告。 我以为我已经破坏了那些。 到底是怎么回事? 我如何完全清除工作区?


attach()不会在您的全局环境中创建xy副本,它会将数据框附加到搜索路径。

来自?attach

The database is not actually attached.  Rather, a new environment
 is created on the search path and the elements of a list
 (including columns of a data frame) or objects in a save file or
 an environment are _copied_ into the new environment.  If you use
 ‘<<-’ or ‘assign’ to assign to an attached database, you only
 alter the attached copy, not the original object.  (Normal
 assignment will place a modified version in the user's workspace:
 see the examples.)  For this reason ‘attach’ can lead to
 confusion.

例如:

> search()
[1] ".GlobalEnv"        "package:stats"     "package:graphics" 
[4] "package:grDevices" "package:utils"     "package:datasets" 
[7] "package:methods"   "Autoloads"         "package:base"     
> a <- data.frame(stuff=rnorm(100))
> search()
[1] ".GlobalEnv"        "package:stats"     "package:graphics" 
[4] "package:grDevices" "package:utils"     "package:datasets" 
[7] "package:methods"   "Autoloads"         "package:base"     
> attach(a)
> search()
 [1] ".GlobalEnv"        "a"                 "package:stats"    
 [4] "package:graphics"  "package:grDevices" "package:utils"    
 [7] "package:datasets"  "package:methods"   "Autoloads"        
[10] "package:base"     
> rm(list=ls())
> search()
 [1] ".GlobalEnv"        "a"                 "package:stats"    
 [4] "package:graphics"  "package:grDevices" "package:utils"    
 [7] "package:datasets"  "package:methods"   "Autoloads"        
[10] "package:base"     
> stuff
  [1] -0.91436377  0.67397624  0.62891651 -0.99669584  2.07692590 -0.62702302
  [...]
> detach(a)
> search()
[1] ".GlobalEnv"        "package:stats"     "package:graphics" 
[4] "package:grDevices" "package:utils"     "package:datasets" 
[7] "package:methods"   "Autoloads"         "package:base"    

只需要提及......如果你的环境中隐藏了对象,比如.First.Last函数,你可以使用rm(list = ls(all.names = TRUE))来删除它们。 但在你的情况下,使用detach(objectname)从搜索路径中删除对象。 detach()将删除位置#2中的任何对象,因为.GlobalEnv不能被删除(并且也是base )。 使用detach()你可以卸载以前加载的软件包,所以要小心(尽管你可以随时加载library(packagename) )。


R本身说,在rm的帮助中:

## remove (almost) everything in the working environment.
## You will get no warning, so don't do this unless you are really sure.
rm(list = ls())

注意'几乎'。 有不同的环境。

你尝试detach(values1)吗?

链接地址: http://www.djcxy.com/p/25007.html

上一篇: rm(list=ls()) doesn't completely clear the workspace

下一篇: Stargazer R Package: Position of Title in Latex Table