Skip to content

Instantly share code, notes, and snippets.

@hypercompetent
Forked from schnee/purrr_happy.R
Last active May 5, 2019 19:11
Show Gist options
  • Save hypercompetent/7aafe8f135dac5ade78145f3460e5e92 to your computer and use it in GitHub Desktop.
Save hypercompetent/7aafe8f135dac5ade78145f3460e5e92 to your computer and use it in GitHub Desktop.
What considerations are important in choosing between the two styles below? Interpretability, maintainability, speed, other?
library(purrr)
library(magrittr)
library(microbenchmark)
y_test <- sample(0:9, 2000, replace = TRUE)
pred1 <- sample(0:9, 2000, replace= TRUE)
pred2 <- sample(0:9, 2000, replace= TRUE)
preds <- list(pred1, pred2)
# want to apply the following to preds
# sum(diag(table(y_test, pred)))/length(y_test)
#
# this
#
preds %>%
map(table, y_test) %>%
map(diag) %>%
map(sum) %>%
map_dbl(divide_by, length(y_test)
#
# or this
#
preds %>%
map_dbl(~{sum(diag(table(y_test, .x)))/length(y_test)})
microbenchmark(
setup = function() {
y_test <- sample(0:9999, 1e6, replace = TRUE)
pred1 <- sample(0:9999, 1e6, replace= TRUE)
pred2 <- sample(0:9999, 1e6, replace= TRUE)
preds <- list(pred1, pred2)
},
# This
readable = function() {
preds %>%
map(table, y_test) %>%
map(diag) %>%
map(sum) %>%
map_dbl(divide_by, length(y_test))
},
# Or This
compact = function() {
preds %>%
map_dbl(~{sum(diag(table(y_test, .x)))/length(y_test)})
},
base = function() {
preds_table <- lapply(preds, table, y_test)
preds_diag <- lapply(preds_table, diag)
preds_sum <- sapply(preds_diag, sum)
preds_sum / length(y_test)
},
times = 1e6
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment