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.
Now, let’s create a new environment.
> chamber <- new.env()
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.
Error: object ‘cup’ not found
Error: object ‘or’ not found
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.
There, your holy grail is safely stored. Now if you can just get it to do the Tribble thing….