From tag at biostat.ku.dk  Thu Apr 18 07:09:12 2013
From: tag at biostat.ku.dk (Thomas Alexander Gerds)
Date: Thu, 18 Apr 2013 07:09:12 +0200
Subject: [Rd] how to control the environment of a formula
Message-ID: <86bo9ce87b.fsf@biostat.ku.dk>

Dear List

I have experienced that objects generated with one of my packages used
a lot of space when saved on disc (object.size did not show this!).

some debugging revealed that formula and call objects carried the full
environment of subroutines along, including even stuff not needed by the
formula or call. here is a sketch of the problem

,----
| test <- function(x){
|   x <- rnorm(1000000)
|   out <- list()
|   out$f <- a~b
|   out
| }
| v <- test(1)
| save(v,file="~/tmp/v.rda")
| system("ls -lah ~/tmp/v.rda")
| 
| -rw-rw-r-- 1 tag tag 7,4M Apr 18 06:41 /home/tag/tmp/v.rda
`----

I tried to replace line 3 by

,----
| as.formula(a~b,env=emptyenv())
| or
| as.formula(a~b,env=NULL)
`----

without the desired effect. Instead adding either

,----
| environment(out$f) <- emptyenv()
| or
| environment(out$f) <- NULL
`----

has the desired effect (i.e. the saved object size is
shrunken). unfortunately there is a new problem:

,----
| test <- function(x){
|   x <- rnorm(1000000)
|   out <- list()
|   out$f <- a~b
|   environment(out$f) <- emptyenv()
|   out
| }
| d <- data.frame(a=1,b=1)
| v <- test(1)
| model.frame(v$f,data=d)
| 
| Error in eval(expr, envir, enclos) : could not find function "list"
`----

Same with NULL in place of emptyenv()

Finally using .GlobalEnv in place of emptyenv() seems to remove both problems.
My questions:

1)  why does the argument env of as.formula have no effect?
2)  is there a better way to tell formula not to copy unrelated stuff
    into the associated environment?
3)  why does object.size not show the size of the environments that
    formulas can carry along?
    
Regards
Thomas    


--
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) 

-- 
--
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) 



[Rd] how to control the environment of a formula
Thomas Alexander Gerds