[R] difference in using with() and the "data" argument in glm call

vito muggeo vmuggeo at dssm.unipa.it
Fri Nov 3 14:25:56 CET 2006


Dear all,
I am dealing with the following (apparently simple problem):
For some reasons I am interested in passing variables from a dataframe 
to a specific environment, and in fitting a standard glm:

dati<-data.frame(y=rnorm(10),x1=runif(10),x2=runif(10))
KK<-new.env()
for(i in 1:ncol(dati)) assign(names(dati[i]),dati[[i]],envir=KK)
#Now the following two lines work correctly:
coef(glm(y~x1+x2,data=KK))
with(KK,coef(glm(y~x1+x2)))

#However if I write the above code inside a function, with() does not 
appear to work..

ff<-function(Formula,Data,method=1){
     KK<-new.env()
     for(i in 1:ncol(Data)) assign(names(Data[i]),Data[[i]],envir=KK)
     o<-if(method==1) glm(Formula,data=KK) else with(KK,glm(Formula))
     o}

 > ff(y~x1+x2,dati,1) #it works
Call:  glm(formula = Formula, data = KK)
..[SNIP]..
 > ff(y~x1+x2,dati,2) #it does not
Error in eval(expr, envir, enclos) : object "y" not found
 >

Could anyone to explain such difference? I believed that
"with(data,glm(formula))" and "glm(formula,data)" were equivalent.

Many thanks,
vito



-- 
====================================
Vito M.R. Muggeo
Dip.to Sc Statist e Matem `Vianelli'
Università di Palermo
viale delle Scienze, edificio 13
90128 Palermo - ITALY
tel: 091 6626240
fax: 091 485726/485612



More information about the R-help mailing list