Friday, April 29, 2011

R farts: Get with it.

As a set up for some more complicated environmental manipulations, .GlobalEnv is a pre-defined reference to the global environment (in the R sense).

With is a function which constructs a local environment from a data argument, and lets you evaluate an expression within that environment.  It returns only the value of the evaluated expression. 

The combination of these two lets you construct data frames with derived objects without polluting the global environment with junk temporary variables.  For example:
df <- data.frame( x = runif(100) )
df <- with( data = df, expr = {
   y = 2*x+1
   z = 3*y^2+1
   df <- data.frame(x = x, y = y, z = z )
   return(df)
})
Even better, if you have some variables pre-calculated in the global environment, you can pull them in using the .GlobalEnv reference:

df <- data.frame( x = runif(100) )
df <- with( data = df, expr = {
   y = 2*x+1
   z =.GlobalEnv$oftenUsedFunction(y)
   df <- data.frame(x = x, y = y, z = z )
   return(df)
})
I probably have pages and pages of R scripts which are somewhat repetitive.  Just not repetitive enough to qualify for a function.  I'm still looking for how to organize them better, but this is a start.

No comments:

Post a Comment