[R] python-like dictionary for R

Petr Savicky savicky at cs.cas.cz
Sat Jan 1 13:59:09 CET 2011


On Fri, Dec 31, 2010 at 04:07:07PM -0800, Martin Morgan wrote:
[...]
> Better to use an environment (and live with reference semantics)
> 
> e <- new.env(parent=emptyenv()); t0 <- Sys.time()
> for (i in seq_len(1e6)) {
>     key <- as.character(i)
>     e[[key]] <- i
>     if (0 == i %% 10000)
>         print(i / as.numeric(Sys.time() - t0))
> }

There is a related thread on R-devel. In particular

  https://stat.ethz.ch/pipermail/r-devel/2010-December/059526.html

also suggests to use an environment, but with hash=TRUE. This
option seems to allow faster access. Using the code

  e <- new.env(parent=emptyenv(), hash=TRUE)
  for (k in seq_len(10)) {
      s <- 0
      ti <- system.time(
          for (i in seq_len(5000)) {
              key <- as.character(10*i + k)
              e[[key]] <- i
              s <- s + e[[key]]
          }
      )
      print(unname(ti["user.self"]))
  }

i get, for example

  [1] 0.146
  [1] 0.149
  [1] 0.151
  [1] 0.13
  [1] 0.15
  [1] 0.131
  [1] 0.131
  [1] 0.115
  [1] 0.111
  [1] 0.143

and with

  e <- new.env(parent=emptyenv())

for example

  [1] 0.247
  [1] 0.453
  [1] 0.661
  [1] 0.868
  [1] 1.079
  [1] 1.29
  [1] 1.507
  [1] 1.724
  [1] 1.947
  [1] 2.172

Petr Savicky.



More information about the R-help mailing list