From therneau at mayo.edu  Tue Jun 17 14:52:16 2014
From: therneau at mayo.edu (Therneau, Terry M., Ph.D.)
Date: Tue, 17 Jun 2014 07:52:16 -0500
Subject: [Rd] model.frame and parent environment
In-Reply-To: <539F7D39.4040606@gmail.com>
References: <d46aec$hcl2i9@ironport9.mayo.edu>
	<CA+COutdDhFezrrQcg2v_fhMoCBb1yXPTe2u+BuSv5R+q1SF-Hw@mail.gmail.com>
	<27747b$8rkcdl@ironport10.mayo.edu> <539F7D39.4040606@gmail.com>
Message-ID: <d46aec$hcvg83@ironport9.mayo.edu>

Duncan,
   You missed the point.  (I sometimes write too tersely, so I take the blame.)  Users are 
writing their own "myfun".  I want model.frame to work for them, without forcing the user 
to learn environment trickery.   The actual question from the user was a call to
        fit <- coxph(formula, data=nd)
        predict(fit, type='expected')
Within the predict call it is model.frame that fails, in the same way that it does in my 
simplified example.

Now within model.frame.coxph (and model.frame.lm) there is the line
       eval(fexpr, env, parent.frame())
where env = environment of the formula and fexpr is an unevaluated call to model.frame. 
My underneath question: why is the enclosure argment ignored in this particular case? 
Parent.frame includes "nd".

I have to admit that I find the non-functional parts of scheme, which R inherited, 
continue to leave me with the emotional response of "why would you add such nastiness to a 
language"?   This leaves me at a disadvantage, I suspect, when trying to trace these 
things out.  I've not yet seen a situation where I would want a formula to reference 
non-local information.

Aside: The horrible decision in S to have "data=" replace rather than augment the scope 
for variable matching caused a lot of grief when calling a model inside a function.  The R 
paradym fixed that, for which I am grateful, but with serious consequences.

Terry T.




On 06/16/2014 06:26 PM, Duncan Murdoch wrote:
> On 16/06/2014, 6:09 PM, Therneau, Terry M., Ph.D. wrote:
>> Copy/paste error in creating my message, should have been:
>>     myfun(y~x, test)
>>
>> The problem is still real.
>
> I believe you that there's a real problem, I just wasn't sure what it was.
>
> When I try your corrected code I get this:
>
> Error in is.data.frame(data) : object 'nd' not found
>
> which is presumably the problem you had.  A simple fix is to add the line
>
> environment(formula) <- environment()
>
> at the start of myfun.  This tells R functions to look in the local
> environment, where it will find nd.
>
> Duncan Murdoch
>
>
>>
>>
>> On 06/16/2014 04:27 PM, Duncan Murdoch wrote:
>>> I think something went wrong in your example: myfun takes a formula as well as a
>>> dataframe, and you only passed the dataframe.
>>>
>>> Duncan Murdoch
>>>
>>>
>>
>



[Rd] model.frame and parent environment
Therneau, Terry M., Ph.D.