Tuesday, February 16, 2016

R: load and environments

When using load(), R will load all objects in the “global environment”, i.e. the interactive workspace:

> load("results.rdata",verbose=T)
Loading objects:
  i
  f
  c
  x

If you want to load data but not clutter the global environment you can use some esoteric constructs:

> e = local({load("results.rdata", verbose=T); environment()})
Loading objects:
  i
  f
  c
  x

Here we load all data into a new environment e.  As suggested by Paul Rubin in the comments, a more readable version of this is:

> e <- new.env()          # by default it is a child of the parent environment
> load("results.rdata", e, verbose=T)
Loading objects:
  i
  f
  c
  x

To interact with the data you can do things like:

> ls(e)
[1] "c" "f" "i" "x"
> e$c
          i        j value
1   seattle new-york 0.225
2   seattle  chicago 0.153
3   seattle   topeka 0.162
4 san-diego new-york 0.225
5 san-diego  chicago 0.162
6 san-diego   topeka 0.126

The $ operator can be used to access the data and ls() is a way to list what is inside the environment. There is an additional function ls.str() to show all structures.

> ls.str(e)
c : 'data.frame':	6 obs. of  3 variables:
 $ i    : chr  "seattle" "seattle" "seattle" "san-diego" ...
 $ j    : chr  "new-york" "chicago" "topeka" "new-york" ...
 $ value: num  0.225 0.153 0.162 0.225 0.162 0.126
f :  num 90
i :  chr [1:2] "seattle" "san-diego"
x : 'data.frame':	6 obs. of  6 variables:
 $ i       : chr  "seattle" "seattle" "seattle" "san-diego" ...
 $ j       : chr  "new-york" "chicago" "topeka" "new-york" ...
 $ level   : num  50 300 0 275 0 275
 $ marginal: num  0 0 0.036 0 0.009 ...
 $ lower   : num  0 0 0 0 0 0
 $ upper   : num  Inf Inf Inf Inf Inf ...

Less typing is needed after an attach such that environment e is added to the search path:

> attach(e)
> c
          i        j value
1   seattle new-york 0.225
2   seattle  chicago 0.153
3   seattle   topeka 0.162
4 san-diego new-york 0.225
5 san-diego  chicago 0.162
6 san-diego   topeka 0.126

Use detach() to remove it from the search path again. With rm() we can delete objects inside an environment (or a complete environment).

> rm(c,envir=e)
> rm(e)
More information: http://adv-r.had.co.nz/Environments.html.