Re: [Rd] help with eval()

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Mon, 18 Apr 2011 20:17:57 -0400

On Mon, Apr 18, 2011 at 5:51 PM, Terry Therneau <therneau_at_mayo.edu> wrote:
> I've narrowed my scope problems with predict.coxph further.
> Here is a condensed example:
>
> fcall3 <- as.formula("time ~ age")
> dfun3 <- function(dcall) {
>    fit <- lm(dcall, data=lung, model=FALSE)
>    model.frame(fit)
> }
> dfun3(fcall3)
>
> The final call fails: it can't find 'dcall'.
>
> The relevant code in model.frame.lm is:
>       env <- environment(formula$terms)
>       if (is.null(env))
>            env <- parent.frame()
>        eval(fcall, env, parent.frame())
>
> If the environment of the formula is .Globalenv, as it is here, the
> contents of parent.frame() are ignored.  Adding a
>           print(ls(parent.frame()))
> statement just above the  final call shows that it isn't a scope issue:
> the variables we want are there.
>
>  I don't understand the logic behind looking for variables in the place
> the formula was first typed (this is not a complaint).  The inability to
> look elsewhere however has stymied my efforts to fix the scoping problem
> in predict.coxph, unless I drop the env(formula) argument alltogether.
> But I assume there must be good reasons for it's inclusion and am
> reluctant to do so.

>

Try using do.call. Using the built in BOD to illustrate, we first try the posted code to view the error:

> fcall3 <- as.formula("demand ~ Time")
> dfun3 <- function(dcall) {

+     fit <- lm(dcall, data=BOD, model=FALSE)
+     model.frame(fit)
+ }

> dfun3(fcall3)

Error in model.frame(formula = dcall, data = BOD, drop.unused.levels = TRUE) :   object 'dcall' not found
>
> # now replace the lm call with a do.call("lm" ...)
> # so that dcall gets substituted before the call to lm:
>
> fcall3 <- as.formula("demand ~ Time")
> dfun3 <- function(dcall) {
+     fit <- do.call("lm", list(dcall, data = BOD, model = FALSE))
+     model.frame(fit)
+ }

> dfun3(fcall3)

  demand Time
1    8.3    1
2   10.3    2
3   19.0    3
4   16.0    4
5   15.6    5
6   19.8    7



-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com

______________________________________________
R-devel_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel
Received on Tue 19 Apr 2011 - 00:21:45 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 Tue 19 Apr 2011 - 07:50:46 GMT.

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

list of date sections of archive