Thomas Alexander Gerds
2013-Mar-20 17:59 UTC
[R] behaviour of formula objects and environment inside functions
Dear List
I am looking for the recommended way to create a formula inside a
function with an empty environment. I tried several versions (see
below), and one of them seemed to work, but I dont understand why there
is a difference between .GlobalEnv and the environment inside a
function. I would be greatful for any reference or explanation or
advice.
Thanks
Thomas
#+BEGIN_SRC R :results output raw :exports results :session *R* :cache yes
test0 <- function(x){
x <- rnorm(1000000)
out <- list()
out$f <- as.formula(u~b,env=NULL)
out
}
test1 <- function(x){
x <- rnorm(1000000)
out <- list(f=formula(u~b))
environment(out$f) <- NULL
out
}
test2 <- function(x){
x <- rnorm(1000000)
out <- list(f=as.formula(u~b,env=emptyenv()))
out
}
v0 <- test0(1)
v1 <- test1(1)
v2 <- test2(1)
x <- rnorm(1000000)
v3 <- formula(u~b)
save(v0,file="~/tmp/v0.rda")
save(v1,file="~/tmp/v1.rda")
save(v2,file="~/tmp/v2.rda")
save(v3,file="~/tmp/v3.rda")
system("ls -lah ~/tmp/v*.rda")
#+END_SRC
#+RESULTS[<2013-03-20 18:56:26> 0dca0a85fb6472b0250968c3d42527ca0310f86e]:
-rw-rw-r-- 1 tag tag 7,4M Mar 20 18:56 /home/tag/tmp/v0.rda
-rw-rw-r-- 1 tag tag 111 Mar 20 18:56 /home/tag/tmp/v1.rda
-rw-rw-r-- 1 tag tag 7,4M Mar 20 18:56 /home/tag/tmp/v2.rda
-rw-rw-r-- 1 tag tag 113 Mar 20 18:56 /home/tag/tmp/v3.rda
--
Thomas A. Gerds -- Assoc. Prof. Department of Biostatistics
University of Copenhagen, ?ster Farimagsgade 5, 1014 Copenhagen, Denmark
Office: CSS-15.2.07 (Gamle Kommunehospital)
tel: 35327914 (sec: 35327901)
Charles Berry
2013-Mar-21 02:03 UTC
[R] behaviour of formula objects and environment inside functions
Thomas Alexander Gerds <tag <at> biostat.ku.dk> writes:> > Dear List > > I am looking for the recommended way to create a formula inside a > function with an empty environment. I tried several versions (see > below), and one of them seemed to work, but I dont understand why there > is a difference between .GlobalEnv and the environment inside a > function. I would be greatful for any reference or explanation or > advice.[snip]>From ?formulaEnvironments: A formula object has an associated environment, and this environment (rather than the parent environment) is used by 'model.frame' to evaluate variables that are not found in the supplied 'data' argument. So write four functions that: 1) creates a formula 2) creates some data 3) evaluates a formula using model.frame (even implicitly with lm(),say) 4) calls the functions from 1, 2, and 3 When you run '4', the result will depend on the environment of data from 2 and the environment of the formula from 1. If they are both in the same environment, fine. If not, you might get lucky and have the data in a place where it will be found nevertheless. If you are really unlucky the '4' function will find some other data that match the formula and use it. HTH, Chuck