Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # benchmarking for
- # http://stackoverflow.com/questions/20538638/how-to-pick-a-value-in-data-table
- codoremifa <- function() {
- for ( i in unique(y[!is.na(y$len),'len'])) {
- y[y$len == i & !is.na(y$len),'Output'] <- y[y$len == i & !is.na(y$len),paste0('Day_',i)]
- }
- y
- }
- sven <- function() {
- cbind(y, output = y[2:4][cbind(seq.int(nrow(y)), y$len)])
- }
- shadow <- function() {
- require(data.table)
- dt <- data.table(y)
- dt[, output:=ifelse(len==1, Day_1, ifelse(len==2, Day_2, Day_3))]
- }
- tonytonov <- function() {
- mat <- rbind(y$Day_1, y$Day_2, y$Day_3)
- y$output <- diag(mat[y$len, ])
- y
- }
- user <- function() {
- cbind(y, output=apply(y, 1, function(r) r[r["len"]+2]))
- }
- N <- 1000
- df <- data.frame(len = sample(c(NA, 1:3), size=N, replace=T),
- Day_1 = 5 + runif(N),
- Day_2 = rnorm(N),
- Day_3 = rbinom(N, 1, 1/2))
- require(rbenchmark)
- benchmark(default(), tonytonov(), sven(), shadow(), codoremifa(), replications=100, order="relative")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement