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

ste*_*ejb 32 r

这是一个非常小的问题,但我想了解到底发生了什么.

说我做以下事情:

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)
Run Code Online (Sandbox Code Playgroud)

此时,我可以做到

rm(list=ls())

values2 <- dbGetQuery("select x,y from table1")
attach(values2)
Run Code Online (Sandbox Code Playgroud)

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

Vin*_*nce 29

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.
Run Code Online (Sandbox Code Playgroud)

例如:

> 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"    
Run Code Online (Sandbox Code Playgroud)

  • 有没有办法在更改后清除 Attach(a) 创建的环境?如果我附加(a),使用列名称作为参考对列进行更改,然后分离(a)后跟附加(a)不会删除这些更改。 (2认同)

aL3*_*3xa 7

提一下......如果你或许在你的环境中有隐藏的对象,比如.First.Last函数,你可以删除它们rm(list = ls(all.names = TRUE)).但在您的情况下,用于detach(objectname)从搜索路径中删除对象.detach()将删除位置#2中的任何对象,因为.GlobalEnv无法删除(base也是).随着detach()您可以卸载先前加载的包,所以要小心(虽然你可以随时加载它们library(packagename)).