# Re: [R] accessing variables inside a function, inside a loop

From: zListserv <zlistserv_at_gmail.com>
Date: Tue, 01 Mar 2011 22:04:43 -0500

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)
[]

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

```

[]

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
______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help