这是一个非常小的问题,但我想了解到底发生了什么。
说我做了以下事情:
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的警告。我以为我已经破坏了那些。到底是怎么回事?如何彻底清除工作区?
答案 0 :(得分:29)
attach()
不会在您的全球环境中制作x
和y
的副本,它会将数据框附加到搜索路径。
来自?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"
答案 1 :(得分:7)
提一下......如果您或许在您的环境中隐藏了对象,例如.First
和.Last
函数,则可以使用rm(list = ls(all.names = TRUE))
删除它们。但在您的情况下,使用detach(objectname)
从搜索路径中删除对象。 detach()
将移除位置#2中的任何对象,因为无法删除.GlobalEnv
(以及base
)。使用detach()
,您可以卸载以前加载的软件包,因此请小心(尽管您始终可以使用library(packagename)
加载它们。)
答案 2 :(得分:3)
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)
吗?
答案 3 :(得分:2)
您很可能至少有一个其他数据框或列表附有x和y列/组件。您可以使用“冲突”功能查看具有潜在冲突的所有对象,并使用“查找”功能找出这些对象的位置(“搜索”功能也有助于显示您附加的所有内容)。
您的问题是为什么附加数据框架不受欢迎的一个很好的例子,最好使用“with”或“within”之类的函数,以免忘记分离对象时出现问题。
答案 4 :(得分:2)
要使用detach()函数从Work Space中删除特定包,它需要包的完整描述。
示例:删除包ISwR 答案1:分离(ISwR)......不行!套餐仍在工作区。 答案2:分离(包裹:ISWR)....工作!包将从工作空间中删除。
答案 5 :(得分:0)
如果您正在使用RStudio,您可以转到Session-&gt; Clear Workspace ... 清除工作区中的所有变量
答案 6 :(得分:-1)
您可以使用:
rm(list=ls())
或:
rm(list=(ls()))
但在关闭R之前保存工作区。