Created
January 31, 2016 20:30
-
-
Save 1beb/3e214b9fb7962174991a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
current_test <- function(df) { | |
for (i in 1:nrow(df)) { # for every row | |
if ((df[i, 'col1'] + df[i, 'col2'] + df[i, 'col3'] + df[i, 'col4']) > 4) { # check if > 4 | |
df[i, 5] <- "greater_than_4" # assign 5th column | |
} else { | |
df[i, 5] <- "lesser_than_4" # assign 5th column | |
} | |
} | |
return(df[,5]) | |
} | |
vectorized_test <- function(df) { | |
output <- character (nrow(df)) | |
for (i in 1:nrow(df)) { | |
if ((df[i, 'col1'] + df[i, 'col2'] + df[i, 'col3'] + df[i, 'col4']) > 4) { | |
output[i] <- "greater_than_4" | |
} else { | |
output[i] <- "lesser_than_4" | |
} | |
} | |
return(df$output) | |
} | |
trueonly_test <- function(df) { | |
output <- character(nrow(df)) | |
condition <- (df$col1 + df$col2 + df$col3 + df$col4) > 4 | |
for (i in (1:nrow(df))[condition]) { # run loop only for true conditions | |
if (condition[i]) { | |
output[i] <- "greater_than_4" | |
} else { | |
output[i] <- "lesser_than_4" | |
} | |
} | |
return(df$output) | |
} | |
ifelse_test <- function(df) { | |
output <- ifelse ((df$col1 + df$col2 + df$col3 + df$col4) > 4, "greater_than_4", "lesser_than_4") | |
return(output) | |
} | |
standard_test <- function(df) { | |
output <- 1 | |
output[df$col1 + df$col2 + df$col3 + df$col4 > 4] <- "greater_than_4" | |
output[output != "greater_than_4"] <- "lesser_than_4" | |
return(output) | |
} | |
rowsums_test <- function(df) { | |
output <- 1 | |
output[rowSums(df) > 4] <- "greater_than_4" | |
output[output != "greater_than_4"] <- "lesser_than_4" | |
return(output) | |
} | |
library(microbenchmark) | |
test_me <- function(e) { | |
col1 <- runif (12^e, 0, 2) | |
col2 <- rnorm (12^e, 0, 2) | |
col3 <- rpois (12^e, 3) | |
col4 <- rchisq (12^e, 2) | |
df <- data.frame (col1, col2, col3, col4) | |
bm <- microbenchmark( | |
#current_test(df), | |
#vectorized_test(df), | |
#trueonly_test(df), | |
ifelse_test(df), | |
standard_test(df), | |
rowsums_test(df), | |
times = 10) | |
return(bm) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment