[R] be careful: using attach in R functions

Uwe Ligges ligges at statistik.uni-dortmund.de
Tue Feb 24 21:32:24 CET 2004



li dongfeng wrote:
> 
> Hi there,
> 
>   I have just found that the ``attach'' function
> can get you into trouble when called many times.
> For example, you have a simulation routine called ``f()'',
> in which you used ``attach'' and no corresponding ``detach''.

Well, attach() may be useful for convenient interactive data analysis.
I'd never use it in a simulation, since you can access all objects
without attaching anything. 
(Well, I suggest not to use it at all, at least to our students ... and
I'm using it only in very rare cases myself.)

Uwe Ligges



> Then you call this function many times. You will find that
> the system performance get slower and slower,
> because you are making the R search path longer and longer.
> So be careful when you use attach in a function!
> 
>   Below is a demonstration of this performance loss,
> you will see a linear growth in CPU time usage.
> Adding a ``detach()'' call at the end of ``f''
> will get rid of this problem.
> 
> ###############################
> f <- function(){
>   theta <- list(one=2.0, two=0.3, three=0.4)
>   attach(theta)
>   x  <- c(one, two, three)
>   sample(x, 1)
> }
> 
> test <- function(n=400){
>   timeu <- numeric(n)
>   for(i in seq(n)){
>     timeu[i] <-
>       system.time({
>         resi <- f()
>       })[3]
>   }
>   plot(timeu)
> }
> test()
> ##############################
> 
> ¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡Li Dongfeng
> ¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡ldf-nospacm at math.pku.edu.cn
> ¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡2004-02-24
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html




More information about the R-help mailing list