[R] Where did lost variables go
Berwin A Turlach
Berwin.Turlach at gmail.com
Tue Dec 31 11:14:40 CET 2013
G'day David,
On Mon, 30 Dec 2013 20:42:53 -0500
David Parkhurst <parkhurs at indiana.edu> wrote:
Some wild guesses in the absence of a reproducible example.
> I have several variables in a data frame that aren't listed by ls()
> after I attach that data frame.
ls() list the objects in the global environment. If you attach a data
frame it is attached to the search path, typically after the global
environment.
Type 'search()' to see your search path.
ls() list the global environment, the first entry in the list and
called ".GlobalEnv". Your data frame should be listed as an object in
that environment.
Assuming the name of your data frame is 'foo', then there should be the
name 'foo' somewhere in the list of names returned by 'search()'.
Assuming 'foo' is listed in the second position, then 'ls(2)' should
list all the objects found at that location of the search path, i.e.
all the variables in your data frame.
> Where did they go,
See above.
> and how can I stop the hidden ones from masking the local ones?
Do you mean with "local ones" those in the global environment and by
"hidden ones" those that you couldn't find? I.e. is there an object
"bar" listed by 'ls()' but also an object "bar" listed by 'ls(2)' (i.e.
your data frame 'foo' contained a variable with name 'bar')? Then it is
the other way round, the local ones are hiding the hidden ones.
For that reason attaching data frames has its dangers. It allows to
easily access the variables in the data frame, but any changes to a
variable creates a local copy. Thus, any change *will* not propagate
back to the data frame!
Hopefully the commands below will clarify further.
Cheers,
Berwin
R> foo <- data.frame(bar=rnorm(2), fubar=runif(2))
R> ls()
[1] "foo"
R> attach(foo)
R> search()
[1] ".GlobalEnv" "foo" "package:stats"
[4] "package:graphics" "package:grDevices" "package:utils"
[7] "package:datasets" "package:methods" "Autoloads"
[10] "package:base"
R> ls(2)
[1] "bar" "fubar"
R> bar
[1] -0.07741633 1.05804653
R> fubar
[1] 0.08516929 0.82718383
R> bar <- "what now"
R> ls()
[1] "bar" "foo"
R> bar
[1] "what now"
R> ls(2)
[1] "bar" "fubar"
R> get("bar", pos=2)
[1] -0.07741633 1.05804653
R> foo
bar fubar
1 -0.07741633 0.08516929
2 1.05804653 0.82718383
R> detach(2)
R> bar
[1] "what now"
R> fubar
Error: object 'fubar' not found
R> foo
bar fubar
1 -0.07741633 0.08516929
2 1.05804653 0.82718383
R> attach(foo)
The following object is masked _by_ .GlobalEnv:
bar
R> bar
[1] "what now"
R> fubar
[1] 0.08516929 0.82718383
R> detach(2)
R> bar
[1] "what now"
R> fubar
Error: object 'fubar' not found
R> foo
bar fubar
1 -0.07741633 0.08516929
2 1.05804653 0.82718383
More information about the R-help
mailing list