[R] object not found inside function
Uwe Ligges
ligges at statistik.uni-dortmund.de
Sat Jun 2 17:22:16 CEST 2007
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
More information about the R-help
mailing list