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
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....
This comment has been removed by the author.
ReplyDelete