[R] behaviour of formula objects and environment inside functions
Thomas Alexander Gerds
tag at biostat.ku.dk
Wed Mar 20 18:59:42 CET 2013
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)
More information about the R-help
mailing list