[R] Extracting elements from list: Is [[ always faster than $ ??
Søren Højsgaard
Soren.Hojsgaard at agrsci.dk
Wed Sep 8 14:31:55 CEST 2010
Dear list
It seems to me that extracting elements from a list using '[[' is somewhat faster than using '$'. For example:
> x <- as.list(1:25)
> names(x) <- letters[1:length(x)]
> dput(x)
structure(list(a = 1L, b = 2L, c = 3L, d = 4L, e = 5L, f = 6L,
g = 7L, h = 8L, i = 9L, j = 10L, k = 11L, l = 12L, m = 13L,
n = 14L, o = 15L, p = 16L, q = 17L, r = 18L, s = 19L, t = 20L,
u = 21L, v = 22L, w = 23L, x = 24L, y = 25L), .Names = c("a",
"b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
"o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y"))
>
> system.time({ for (ii in 1:1000000) x[[21]] })
user system elapsed
0.55 0.00 0.54
> system.time({ for (ii in 1:1000000) x[["u"]]})
user system elapsed
0.84 0.00 0.84
> system.time({ for (ii in 1:1000000) x$u})
user system elapsed
1.12 0.00 1.13
Does anyone know if this is always the case? (I have not found anything about speed in this connection on the help pages, apologies if I have overlooked something).
I use R.2.11.1 on Windows 7.
Regards
More information about the R-help
mailing list