[R] macro facility in R

Duncan Murdoch murdoch at stats.uwo.ca
Mon Jul 3 14:15:03 CEST 2006


On 7/3/2006 7:39 AM, John Sorkin wrote:
> R 2.2 on windows XP
> I have a dataset with multiple columns. Some of the columns represent
> independent variables, some represent dependent variables. I would like
> to run the same analyses on a fixed set of independent variables,
> changing only the dependent variable, e.g.
> y1-y2=x1+x2+x3
> y3-y4=x1+x2+x3
> y5-y6=x1+x2+x3, etc.
> I know I can write a function to perform the analyses, however in order
> to make the analyses easy to do, I really need a macro scripting
> language that will allow preprocessing of the function and substitution
> of macro variables with parameters passed to the macro, i.e. I need
> someting akin to the macro facility in SAS. Is there a macro facility
> that I can use with R? I have tried help.search("macro") and did not
> have any success.

I think the substitute function in R does most of what you would want 
from a macro facility.

For example,

 > analyze <- function(dependent, data) {
+   formula <- as.formula(substitute(dep ~ x1 + x2 + x3,
+                         list(dep=substitute(dependent))))
+   lm(formula=formula, data=data)
+ }
 >
 > dat <- data.frame(y = rnorm(10)+1:10, x1=rnorm(10)+1:10, 
x2=rnorm(10), x3=rnorm(10))
 >
 > analyze(y, dat)

Call:
lm(formula = formula, data = data)

Coefficients:
(Intercept)           x1           x2           x3
      1.1256       0.8248       0.1671      -0.1907


I used substitute twice:  the inner call gets the unevaluated expression 
that was passed as "dependent"; the outer one puts that in place of the 
"dep" variable.

Duncan Murdoch



More information about the R-help mailing list