Skip to content
Prev 299064 / 398506 Next

Is it possible to remove this loop? [SEC=UNCLASSIFIED]

On 2012-07-03 17:23, Jin.Li at ga.gov.au wrote:
Interesting. My testing shows that Petr's solution is about
twice as fast. Not that it matters much - the time is pretty
small in any case.

  a0 <- data.frame(h1 = sample(c("H","J","K"), 1e7, replace = TRUE),
                   stringsAsFactors = FALSE)
  a1 <- a0
  system.time({a1$h2 <- 0; a1$h2[a1$h1 == "H"] <- 1})
  #   user  system elapsed
  #   1.47    0.48    1.96
  a11 <- a1

  a1 <- a0
  system.time(a1$h2 <- (a1$h1 == "H") * 1)
  #  user  system elapsed
  #  0.37    0.17    0.56
  a12 <- a1
  all.equal(a11,a12)
  #[1] TRUE

Peter Ehlers