如何通过循环附加环境?

时间:2019-05-09 20:29:47

标签: r variables search environment

我试图通过循环附加多个环境。

env.a <- new.env()
env.b <- new.env()
env.c <- new.env()

attach(env.a)
search()
 [1] ".GlobalEnv"        "env.a"             "package:stats"    
 [4] "package:graphics"  "package:grDevices" "package:utils"    
 [7] "package:datasets"  "package:methods"   "Autoloads"        
[10] "package:base"    
detach(env.a)

# Now do it in a loop
for (e in c("env.a", "env.b", "env.c")) {
+ if (!e %in% search()) { attach(get(e)) }
+ }
search()
 [1] ".GlobalEnv"        "get(e)"            "get(e)"           
 [4] "get(e)"            "package:stats"     "package:graphics" 
 [7] "package:grDevices" "package:utils"     "package:datasets" 
[10] "package:methods"   "Autoloads"         "package:base"     

如以上示例所示,如果仅附加了一个变量,则该方法有效。当我使用循环将它们一个接一个地附加时,它们在搜索路径中将全部命名为get(e)。但是,如果我不使用get(e),则会导致错误。

for (e in c("env.a", "env.b", "env.c")) {
+ if (!e %in% search()) { attach(e) }
+ }
Error in attach(e) : file 'env.a' not found

有人知道这样做的正确方法吗? 谢谢,

1 个答案:

答案 0 :(得分:0)

感谢@PoGibas的评论,以循环方式附上

> for (e in c("env.a", "env.b", "env.c")) {
+ if (!e %in% search()) { attach(get(e), name = e) }
+ }
> search()
 [1] ".GlobalEnv"        "env.c"             "env.b"            
 [4] "env.a"             "package:stats"     "package:graphics" 
 [7] "package:grDevices" "package:utils"     "package:datasets" 
[10] "package:methods"   "Autoloads"         "package:base"

相反,要循环分离

> for (e in c("env.a", "env.b", "env.c")) {
+ if (e %in% search()) { 
+ detach(e, character.only = TRUE) }
+ }
> search()
[1] ".GlobalEnv"        "package:stats"     "package:graphics" 
[4] "package:grDevices" "package:utils"     "package:datasets" 
[7] "package:methods"   "Autoloads"         "package:base"