-
Notifications
You must be signed in to change notification settings - Fork 3
Setting Environments
morota edited this page Dec 19, 2012
·
1 revision
Suppose there is a *.rda file which contains x and y variables.
x <- 1:5
y <- 10:20
save(x, y, file="xy.rda")Further, suppose in a different session, we have x and y variables defiend in the global workspace.
x <- 100
y <- 200If we try to load x and y variables from xy.rda here, it will accidently overwrite current x and y in the global workspace. There are couple of ways to put loaded objects to separate place in the search path.
# ex1
env1 <- new.env()
g <- load("xy.rda", envir=env1)
get(g[1], env1)
[1] 1 2 3 4 5
get(g[2], env1)
[1] 10 11 12 13 14 15 16 17 18 19 20
mget(ls(env1), env1)
$x
[1] 1 2 3 4 5
$y
[1] 10 11 12 13 14 15 16 17 18 19 20
# x and y in the global environment (not overwritten)
x
[1] 100
y
[1] 200
# ex2
env2 <- local({load("xy.rda"); environment()})
env2$x
[1] 1 2 3 4 5
env2$y
[1] 10 11 12 13 14 15 16 17 18 19 20
# x and y in the global environment (not overwritten)
x
[1] 100
y
[1] 200
# ex3
env3 <- attach(NULL, pos=2, name="myenv")
load("xy.rda", envir=env3)
env3$x
[1] 1 2 3 4 5
env3$y
[1] 10 11 12 13 14 15 16 17 18 19 20
search()
[1] ".GlobalEnv" "myenv" "package:stats"
[4] "package:graphics" "package:grDevices" "package:utils"
[7] "package:datasets" "package:fortunes" "package:methods"
[10] "Autoloads" "package:base"
detach()
search()
[1] ".GlobalEnv" "package:stats" "package:graphics"
[4] "package:grDevices" "package:utils" "package:datasets"
[7] "package:fortunes" "package:methods" "Autoloads"
[10] "package:base"
# x and y in the global environment (not overwritten)
x
[1] 100
y
[1] 200
# ex4
env4 <- attach("xy.rda")
The following object(s) are masked _by_ '.GlobalEnv':
x, y
env4$x
[1] 1 2 3 4 5
env4$y
[1] 10 11 12 13 14 15 16 17 18 19 20
ls(pos=2)
[1] "x" "y"
search()
[1] ".GlobalEnv" "file:xy.rda" "package:stats"
[4] "package:graphics" "package:grDevices" "package:utils"
[7] "package:datasets" "package:fortunes" "package:methods"
[10] "Autoloads" "package:base"
detach()
search()
[1] ".GlobalEnv" "package:stats" "package:graphics"
[4] "package:grDevices" "package:utils" "package:datasets"
[7] "package:fortunes" "package:methods" "Autoloads"
[10] "package:base"
# x and y in the global environment (not overwritten)
x
[1] 100
y
[1] 200