Re: [R] object not found inside function

From: Uwe Ligges <ligges_at_statistik.uni-dortmund.de>
Date: Sat, 02 Jun 2007 17:22:16 +0200

Maria Montez wrote:
> Hi!
>
> When running the following code I get the message: Error in eval(expr,
> envir, enclos) : object "A" not found
>
> fm <- function(p,ydata, env = parent.frame()) {
> #fit model y ~ (b0+b1x1+...+bpxp)*exp(g2plus*z2plus) where bi and g2plus
> are parameters
>
> #create design matrix for linear part
> fo00 <- paste("~",paste(paste("x",1:p,sep=""),collapse="+"),sep="")
> fo0 <- as.formula(fo00)
> A <- model.matrix(fo0,data=ydata)
>
> # create z variable
> z2plus <- ifelse(totx>1,1,0)
> ydata <- data.frame(ydata,z2plus)
>
> #run model
> t2 <- nls(y ~
> A*exp(g2plus*z2plus),data=ydata,start=c(g2plus=0),alg="plinear")
> }
> model <- fm(4,ydata)
>
> The code inside the function works if not enclosed in a function. This
> makes me think that it is a scope problem and I need to specify the
> environment. Even though I've read about environment and lexical scope I
> still don't fully understand how it works. Sometimes I can do it others
> I can't!
>
> Can someone help me?
>
> I've included below code to create a dataframe that can be used to test
> my code.
>
> Thanks, Maria
>

[data deleted]

Maria,

  1. Do you really want to paste() the formula fo0 together that way?
  2. For me, the functions fails because totx is not known. Please make sure to post *reproducible* code (OK, you almost did).
  3. If totx is known, the function works for me, hence I guess you are using an outdated version (< 2.5.0) of R. --> Please always specify the version of R and the OS you are using.

Uwe



R-help_at_stat.math.ethz.ch 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. Received on Sat 02 Jun 2007 - 15:35:43 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sat 02 Jun 2007 - 16:31:41 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.