Created
January 7, 2020 19:03
-
-
Save cimentadaj/ddc8d0be38e4f3268a91da9d24acdf82 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
library(tidyverse) | |
set.seed(23131) | |
original_matrix <- replicate(10, sample(1:10, 10, replace = TRUE)) | |
my_params <- tibble(x = sample(1:10, 5, replace = TRUE), | |
y = sample(2:3, 5, replace = TRUE)) | |
# Define the matrix that will be updated in each iteration | |
my_matrix <- original_matrix | |
my_function2 <- function(param1, param2) { | |
# In each iteration, multiply by your params | |
# and update `my_matrix` in the global environment | |
# This ensures that in every interation you're getting | |
# the up to date `my_matrix`. | |
my_matrix <<- (my_matrix + param1) * param2 | |
my_matrix | |
} | |
final_res <- map2(my_params$x, | |
my_params$y, | |
my_function2) | |
final_res[[nrow(my_params)]] | |
iter_fun <- function(param1, param2, matrix) { | |
i <- 1 | |
max <- length(param1) | |
orig_m <- (matrix + param1[i]) * param2[i] | |
test_fun <- function() { | |
while (i < max) { | |
orig_m <<- (orig_m + param1[i + 1]) * param2[i + 1] | |
i <<- i + 1 | |
} | |
orig_m | |
} | |
test_fun() | |
} | |
res <- microbenchmark::microbenchmark( | |
purrr = map2(my_params$x, | |
my_params$y, | |
my_function2), | |
base = iter_fun(my_params$x, | |
my_params$y, | |
original_matrix) | |
) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment