As you suggested, David, the code below works. Now I it can find the weights - because they are in the data frame x. But how can I be sure now that it actually grabs the data from the data frame "variables" and not the data frame x?
x<-data.frame(y=rnorm(100,0,1),a=rnorm(100,1,1),b=rnorm(100,2,1),myweights=runif(100)) names(x) weighted.reg=function(formula, MyData, filename,WeightsVector) { variables<-MyData[1:(length(MyData)-1)] # creating a data frame without the weights print(dim(MyData)) print(filename) print(length(WeightsVector)) regr.f<-lm(formula,variables,weights=WeightsVector,na.action=na.omit) results<-as.data.frame(round(summary(regr.f)$coeff,3)) write.csv(results,file=filename) return(results) } reg2<-weighted.reg(y~., MyData=x, filename="TEST.csv", WeightsVector=x$myweights) Dimitri On Fri, Oct 22, 2010 at 9:15 AM, David Winsemius <dwinsem...@comcast.net> wrote: > > On Oct 22, 2010, at 9:01 AM, Dimitri Liakhovitski wrote: > >> Dear R'ers, >> >> I am fighting with a problem that is driving me crazy. I use "lm" in >> my user-defined function, but it seems to be looking for weights >> outside of my function's environment: >> >> ### Generating example data: >> x<-data.frame(y=rnorm(100,0,1),a=rnorm(100,1,1),b=rnorm(100,2,1)) >> myweights<-runif(100) >> data.for.regression<-x[1:3] >> >> ### Creating function "weighted.reg": >> weighted.reg=function(formula, MyData, filename,WeightsVector) >> { >> print(dim(MyData)) >> print(filename) >> print(length(WeightsVector)) >> regr.f<-lm(formula,MyData,weights=WeightsVector,na.action=na.omit) >> results<-as.data.frame(round(summary(regr.f)$coeff,3)) >> write.csv(results,file=filename) >> return(results) >> } >> >> ### Running "weighted.reg" with my data: >> reg2<-weighted.reg(y~., MyData=x, WeightsVector=myweights, >> filename="TEST.csv") >> >> >> I get an error: Error in eval(expr, envir, enclos) : object >> 'WeightsVector' not found >> Notice, that the function correctly prints length(WeightsVector). But >> it looks like "lm" is looking for weights (in the 4th line of the >> function) OUTSIDE the function and does not see WeightsVector. > > Have you tried putting WeightsVector in the "x" dataframe? That would seem > to reduce the potential for environmental conflation. > > From the details section of help(lm): > "All of weights, subset and offset are evaluated in the same way as > variables in formula, that is first in data and then in the environment of > formula." > > >> Why is it looking outside the function for the object that has just >> been defined inside the function? >> > > > David Winsemius, MD > West Hartford, CT > > -- Dimitri Liakhovitski Ninah Consulting www.ninah.com ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.