Re: [R] Problem with object inside a function

From: Duncan Murdoch <murdoch_at_stats.uwo.ca>
Date: Sun, 20 Apr 2008 10:56:13 -0400

On 20/04/2008 9:40 AM, Ronaldo Reis Junior wrote:
> Hi all,
>
> I have a problem with an object inside a formula in a function that I make.
>
> I create an object named qvartemp. This object is OK, look the levels:
>

>> print(levels(qvartemp))

> [1] "baixomedio" "alto"
>
> Now I create a new object with a new formula:
>
>> new.form <- as.formula(gsub(qvar,"qvartemp",as.expression(mma$formula)))

>
> Look this new object:
>
>> print(new.form)

> Riqueza ~ Biomassa * qvartemp
>
> Now here is the problem, I try to update an existing model (mma) changing the
> formula by the new.form
>
> mmaa <- update(mma,new.form)
>
> But my function is aborted with this message:
>
> Error in eval(expr, envir, enclos) : object "qvartemp" not found
>
> If I create this object qvartemp in R section manually it my function work,
> because it get the object from my workspace (but it is usefull just for
> testing), but my function dont find this object qvartemp created inside the
> function.
>
> If I run all my function line by line without use the function it work, I
> think that is because in this case the object is created in my workspace. But
> when I run a function the object is created only in memory (not in my
> workspece) and in this case update dont find this object.
>
> Anybody can suggest any Idea to fix it? I necessary I send my function and a
> example.

Formulas have attached environments; that's where they look for the variables they use. You created new.form, but didn't give it the environment of the old one.

I think all you need is

environment(new.form) <- environment(mma$formula)

Duncan Murdoch



R-help_at_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. Received on Sun 20 Apr 2008 - 15:49:10 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 Sun 20 Apr 2008 - 17:30:35 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.

list of date sections of archive