[R] behaviour of formula objects and environment inside functions

Charles Berry ccberry at ucsd.edu
Thu Mar 21 03:03:52 CET 2013


Thomas Alexander Gerds <tag <at> biostat.ku.dk> writes:

> 
> Dear List
> 
> I am looking for the recommended way to create a formula inside a
> function with an empty environment. I tried several versions (see
> below), and one of them seemed to work, but I dont understand why there
> is a difference between .GlobalEnv and the environment inside a
> function. I would be greatful for any reference or explanation or
> advice.
[snip]

>From ?formula

Environments:

     A formula object has an associated environment, and this
     environment (rather than the parent environment) is used by
     'model.frame' to evaluate variables that are not found in the
     supplied 'data' argument.

So write four functions that:

1) creates a formula
2) creates some data
3) evaluates a formula using model.frame (even implicitly with lm(),say)
4) calls the functions from 1, 2, and 3

When you run '4', the result will depend on the environment of data from 2
and the environment of the formula from 1. If they are both in the same
environment, fine. If not, you might get lucky and have the data in a place
where it will be found nevertheless. 

If you are really unlucky the '4' function will find some other data that 
match the formula and use it.

HTH,

Chuck



More information about the R-help mailing list