[R] referring to calls in functions

Charles C. Berry cberry at tajo.ucsd.edu
Wed Jan 14 04:08:01 CET 2009


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

> The first program generates an error message and does not execute the
> regression of y on x.
>
>
>        x<-1:10;
>        y<-rnorm(10) + x;
>
>        prac <- function( model, wghts ){ lm(model, weights = wghts) }
>
>        prac(model = y~x, wghts = rep(1, 10))
>
>
>
> But the next program works:
>
>        x<-1:10;
>        y<-rnorm(10) + x;
>
>        prac <- function( y, x, wghts ){ lm(y~x, weights = wghts) }
>
>        prac(y=y, x=x, wghts = rep(1, 10))
>
>
> I would be grateful for an explanation of why the first program does not
> work. It seems to me like they should both give the same result.

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

>
>
>
>
>
> Joe Boyer
> Statistical Sciences
> Renaissance Bldg 510, 3233-D
> Mail Stop RN0320
> 8-275-3661
> cell: (610) 209-8531
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

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




More information about the R-help mailing list