[R] Assigning a class attribute to a list or vector slows "[" down

From: Søren Højsgaard <Soren.Hojsgaard_at_agrsci.dk>
Date: Tue, 05 Apr 2011 01:29:37 +0200


Dear list,
I've noticed that if a list or a vector is given a class (by class(x) <- "something") then the "selection operator slows down - quite a bit. For example:

> lll <- as.list(letters)
> system.time({for(ii in 1:200000)lll[-(1:4)]})

   user system elapsed
   0.48 0.00 0.49
>
> class(lll) <- "foo"
> system.time({for(ii in 1:200000)lll[-(1:4)]})

   user system elapsed
   2.57 0.00 2.58
>
> vvv <- 1:100
> system.time({for(ii in 1:200000)vvv[-(1:4)]})

   user system elapsed
   0.71 0.00 0.72
>
> class(vvv) <- "foo"
> system.time({for(ii in 1:200000)vvv[-(1:4)]})

   user system elapsed
   2.85 0.00 2.87
I guess that what happens is that R looks for a "["-method for for "foo" objects and when such a method is not found, a default "["-method is called? Is that so?

What should one do to avoid such a slowdown when wanting to select elements from a list or a vector with a class? Using unclass is one option:

> class(vvv) <- "foo"
> system.time({for(ii in 1:200000)unclass(vvv)[-(1:4)]})

   user system elapsed
   0.94 0.00 0.94
Are there better ways?

Best regards
Søren

PS: I am using R.2.12.2 on windows 7.



R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Mon 04 Apr 2011 - 23:35:13 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 04 Apr 2011 - 23:40:27 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive