Home Away From Home

May 2, 2011
By

(This article was first published on Milk Trader, and kindly contributed to R-bloggers)

It used to be stuffed animals everywhere. These days, it's those annoyingly small lego pieces. Toys in the house have a certain Tribble quality to them. They propagate during some designated time in the middle of the night and in the morning, they are everywhere. Worse than ants, because you can kill the ants. Invariably, a parent must do the dreaded task of "quote" -- renting a storage unit. These are temporary homes for these toys, and a temporary relief for grownups.

Programming in R has similar hazards with a cluttered space. Fortunately, the godly designers anticipated this issue and created a concept known as environments. When you're curve-fitting your latest brainstorm in the R environment, you are (perhaps unbeknownst to yourself) manipulating objects in the global environment. This is your main home. If it gets cluttered, you can easily create a storage unit within this space. It keeps things out of the house and stuffed in a closet. But in a really organized way so you can get stuff easily.

Some code for illustration. First, I'm going to create a new environment, or storage unit if you will. Then I'll stuff a few objects in it, see if I can call them from the global environment (hint: I can't) and then call them successfully from the designated environment. Below, the ">" symbol is the prompt from within the R console.

Let's start fresh and remove all objects from the global environment with the rm() function.

> rm(list=ls())
> ls()
character(0)


Now, let's create a new environment.

> chamber <- new.env()
> ls()
[1] "chamber"


Then let's create some variables (just some character strings for illustration) and assign them to the environment.


> chamber$cup  <- "hole"
> chamber$or  <- "E"
> chamber$chalice <- "grail"


Next, let's see if we can find them in our global environment.


> cup
Error: object 'cup' not found
> or
Error: object 'or' not found
> chalice
Error: object 'chalice' not found


This was expected of course, and is the point. Your home is clear of the clutter. Now let's call those objects with the correct syntax, acknowledging where we put them.


> chamber$cup
[1] "hole"
> chamber$or
[1] "E"
> chamber$chalice
[1] "grail"



There, your holy grail is safely stored. Now if you can just get it to do the Tribble thing....

To leave a comment for the author, please follow the link and comment on his blog: Milk Trader.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags: ,

Comments are closed.