Thomas, Jeff, Mark, Antonio,

Thank you for your answers. They have helped me clarify how R functions 
work. They work differently from SAS functions (which SAS calls macros.)

If you know SAS, consider the following code:

*********************
%macro q(y);

data one;
outvar = &y. + &x.; output;
call symputx("outvar", outvar, "G");
run;

%mend;

%macro w(x);

%q(&x.);
%put &outvar.;

%mend;
**************

Then %w(2); will result in the value 4 being placed in the SAS log.


To me, while the coding is quite awkward, the execution is logical. The 
variable x has been defined by the call to the macro w, so there is no 
problem when SAS encounters a reference to x in the macro q.

But in the equivalent code in R, 

q <- function(y) y +x; w <- function(x) q(x); w(2);

when R can't find the second argument of q in the local environment of the 
macro q, it doesn't look in the local environment of the macro w, it goes 
all the way back to 
the global environment, as you have all pointed out.

So in my little model of how R functions work, when a function is called

1. R rewrites the body of the function, replacing all of the parameter 
names with the values given to them in the function call.

2. R then tries to execute the expressions. But R only "remembers" the 
assignment of values to parameter names during step 1. Thus in our example
        it has to go the global environment to find a value for "x" 
referenced in q.

Is this right?








Joe Boyer
Statistical Sciences 
Renaissance Bldg 510, 3233-D
Mail Stop RN0320
8-275-3661
cell: (610) 209-8531
	[[alternative HTML version deleted]]

