Skip to content
Prev 166914 / 398502 Next

referring to calls in functions

On Tue, 13 Jan 2009, joseph.g.boyer at gsk.com wrote:

            
See

 	?formula

especially the part about 'Environment'

and

 	?model.frame

(which lm() uses to gather up the objects it needs)

In the first instance, the environment of the formula is R_GlobalEnv, but 
that of 'wghts' is the environment created for the evaluation of 
prac(...).

In the second instance, both formula and 'wghts' share the same 
environment.

The rules model.frame() uses allow the second to 'work', while 
model.frame() never 'sees' 'wghts' in the first case.

----

There are numerous discussions in the archives on how to deal with this, 
why R is designed like this, whether it ought to change, ....

There are various approaches.

One approach to your case is to use

 	environment( model ) <- environment()

as the first line of your function to get model.frame to look first in the 
environment of the function calling lm(). This will work in your case, but 
might be troublesome in others (as when you assign the value of prac() 
and subsequently try to find 'model').

Another approach to your case is to use

 	cur.env <- environment()
 	lm( model, weights, data = cur.env )

in your function, which doesn't tinker with environment(model) and forces 
model frame to start with 'cur.env' to look up objects. Obviously, this 
will cause trouble if you want to pass a  'data' arg thru prac().

HTH,

Chuck
Charles C. Berry                            (858) 534-2098
                                             Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	            UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/  La Jolla, San Diego 92093-0901