[R] Assigning a class attribute to a list or vector slows "[" down
Søren Højsgaard
Soren.Hojsgaard at agrsci.dk
Tue Apr 5 01:29:37 CEST 2011
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.
More information about the R-help
mailing list