Advertisement
tonytonov

SO R benchmarking

Dec 12th, 2013
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.02 KB | None | 0 0
  1. # benchmarking for
  2. # http://stackoverflow.com/questions/20538638/how-to-pick-a-value-in-data-table
  3.  
  4. codoremifa <- function() {
  5.   for ( i in unique(y[!is.na(y$len),'len']))  {
  6.     y[y$len == i & !is.na(y$len),'Output'] <- y[y$len == i & !is.na(y$len),paste0('Day_',i)]
  7.   }
  8.   y
  9. }
  10.  
  11. sven <- function() {
  12.   cbind(y, output = y[2:4][cbind(seq.int(nrow(y)), y$len)])
  13. }
  14.  
  15. shadow <- function() {
  16.   require(data.table)
  17.   dt <- data.table(y)
  18.   dt[, output:=ifelse(len==1, Day_1, ifelse(len==2, Day_2, Day_3))]
  19. }
  20.  
  21. tonytonov <- function() {
  22.   mat <- rbind(y$Day_1, y$Day_2, y$Day_3)
  23.   y$output <- diag(mat[y$len, ])
  24.   y
  25. }
  26.  
  27. user <- function() {
  28.   cbind(y, output=apply(y, 1, function(r) r[r["len"]+2]))
  29. }
  30.  
  31. N <- 1000
  32. df <- data.frame(len = sample(c(NA, 1:3), size=N, replace=T),
  33.                  Day_1 = 5 + runif(N),
  34.                  Day_2 = rnorm(N),
  35.                  Day_3 = rbinom(N, 1, 1/2))
  36.  
  37. require(rbenchmark)
  38. benchmark(default(), tonytonov(), sven(), shadow(), codoremifa(), replications=100, order="relative")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement