[R] eval and parent.frame [was: Error in Design package: dataset not found for options(datadist)]
Gad Abraham
gabraham at csse.unimelb.edu.au
Fri Apr 18 04:51:53 CEST 2008
Frank E Harrell Jr wrote:
> Gad Abraham wrote:
>> Hi,
>>
>> Design isn't strictly an R base package, but maybe someone can explain
>> the following.
>>
>> When lrm is called within a function, it can't find the dataset dd:
>>
>> > library(Design)
>> > age <- rnorm(30, 50, 10)
>> > cholesterol <- rnorm(30, 200, 25)
>> > ch <- cut2(cholesterol, g=5, levels.mean=TRUE)
>> > fit <- function(ch, age)
>> + {
>> + d <- data.frame(ch, age)
>> + dd <- datadist(d)
>> + options(datadist="dd")
>> + lrm(ch ~ age, data=d, x=TRUE, y=TRUE)
>> + }
>> > fit(ch, age)
>> Error in Design(eval(m, sys.parent())) :
>> dataset dd not found for options(datadist=)
>>
>> It works outside a function:
>> > d <- data.frame(ch, age)
>> > dd <- datadist(d)
>> > options(datadist="dd")
>> > l <- lrm(ch ~ age, data=d, x=TRUE, y=TRUE)
>>
>>
>> Thanks,
>> Gad
>
> My guess is that you'll need to put dd in the global environment, not in
> fit's environment. At any rate it is inefficient to call datadist every
> time. Why not call it once for the whole data frame containing all the
> predictors, at the top of the program?
This is just sample code, in practice the datadist will be different for
each invocation of the function.
I think it boils down to this behaviour, which I don't understand ---
although ls can see x in the parent of f2, eval cannot:
f1 <- function()
{
x <- 3
f2()
}
f2 <- function()
{
p <- parent.frame()
a <- ls(envir=p)
print(a)
b <- eval(x, envir=p)
print(b)
}
> f1()
[1] "x"
Error in eval(x, envir = p) : object "x" not found
?parent.frame says:
"The parent frame of a function evaluation is the environment in
which the function was called. It is not necessarily numbered one
less than the frame number of the current evaluation, nor is it
the environment within which the function was defined."
I read this to mean that the parent frame of f2 should be f1.
What's happening here?
--
Gad Abraham
Dept. CSSE and NICTA
The University of Melbourne
Parkville 3010, Victoria, Australia
email: gabraham at csse.unimelb.edu.au
web: http://www.csse.unimelb.edu.au/~gabraham
More information about the R-help
mailing list