[R] accessing variables inside a function, inside a loop

zListserv zlistserv at gmail.com
Wed Mar 2 04:04:43 CET 2011


Joshua

Great solution.  Taking off on your code, the following works but does not display the names of the variables in the formula.  Any suggestions about how to modify the function so that it displays the correct formula (e.g., "glm(formula = y1 ~ x1 * x2, data = dat)" instead of "glm(formula = frm, data = dat)")?

R> x = runif(2000)
R> y = runif(2000)
R> z = runif(2000)
R> 
R> y1 = y * x
R> y2 = y * sqrt(x)
R> 
R> x1 = y1 / y2 + z
R> x2 = y2 / y1 * z + z
R> 
R> dat = data.frame(y1,y2,x1,x2)
R>
R> xReg = function(y) {
+ 
+ 	frm = eval(substitute(p ~ x1 * x2, list(p = as.name(y))))
+ 	mod = glm(frm, data=dat)
+ 	}
R> 
R> lapply(names(dat[,1:2]), xReg)
[[1]]

Call:  glm(formula = frm, data = dat)

Coefficients:
(Intercept)           x1           x2        x1:x2  
-0.1882452    0.4932059    0.0667401   -0.1310084  

Degrees of Freedom: 1999 Total (i.e. Null);  1996 Residual
Null Deviance:	    99.15032 
Residual Deviance: 67.71775 	AIC: -1085.354 

[[2]]

Call:  glm(formula = frm, data = dat)

Coefficients:
(Intercept)            x1            x2         x1:x2  
-0.005464627   0.386937367   0.037363416  -0.094136334  

Degrees of Freedom: 1999 Total (i.e. Null);  1996 Residual
Null Deviance:	    112.7078 
Residual Deviance: 90.24796 	AIC: -510.9287 

---

Thanks,

Alan


More information about the R-help mailing list