You can write your code more defensively. There are a few ways to do that:
(B
(B1. Right after the attach(object), do on.exit(detach(object)).
(B2. If you know the function will be call repeatedly, it might be a good idea
(Bto check whether the object has been attached. This way you only need to
(Battach once. I can think of a couple of way to do that. The simplest is
(Bprobably to check and see if the object name appear in the search list.
(B
(BAndy
(B
(B> -----Original Message-----
(B> From: [EMAIL PROTECTED]
(B> [mailto:[EMAIL PROTECTED] On Behalf Of li dongfeng
(B> Sent: Monday, February 23, 2004 1:00 PM
(B> To: [EMAIL PROTECTED]
(B> Subject: [R] be careful: using attach in R functions
(B>
(B>
(B> Hi there,
(B>
(B> I have just found that the ``attach'' function
(B> can get you into trouble when called many times.
(B> For example, you have a simulation routine called ``f()'',
(B> in which you used ``attach'' and no corresponding ``detach''.
(B> Then you call this function many times. You will find that
(B> the system performance get slower and slower,
(B> because you are making the R search path longer and longer.
(B> So be careful when you use attach in a function!
(B>
(B> Below is a demonstration of this performance loss,
(B> you will see a linear growth in CPU time usage.
(B> Adding a ``detach()'' call at the end of ``f''
(B> will get rid of this problem.
(B>
(B> ###############################
(B> f <- function(){
(B> theta <- list(one=2.0, two=0.3, three=0.4)
(B> attach(theta)
(B> x <- c(one, two, three)
(B> sample(x, 1)
(B> }
(B>
(B> test <- function(n=400){
(B> timeu <- numeric(n)
(B> for(i in seq(n)){
(B> timeu[i] <-
(B> system.time({
(B> resi <- f()
(B> })[3]
(B> }
(B> plot(timeu)
(B> }
(B> test()
(B> ##############################
(B>
(B>
(B> $B!!!!!!!!!!!!!!!!(JLi Dongfeng
(B> $B!!!!!!!!!!!!!!!!([EMAIL PROTECTED]
(B> $B!!!!!!!!!!!!!!!!!!!!(J2004-02-24
(B>
(B> ______________________________________________
(B> [EMAIL PROTECTED] mailing list
(B> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
(B> PLEASE do read the posting guide!
(B> http://www.R-project.org/posting-guide.html
(B>
(B>
(B
(B
(B------------------------------------------------------------------------------
(BNotice: This e-mail message, together with any attachments,...{{dropped}}
(B
(B______________________________________________
(B[EMAIL PROTECTED] mailing list
(Bhttps://www.stat.math.ethz.ch/mailman/listinfo/r-help
(BPLEASE do read the posting guide! http://www.R-project.org/posting-guide.html