Skip to content

Instantly share code, notes, and snippets.

@grantmcdermott
Last active April 13, 2020 22:31
Show Gist options
  • Save grantmcdermott/28aad7b6a5cedb01dc0fe73f51ca3e57 to your computer and use it in GitHub Desktop.
Save grantmcdermott/28aad7b6a5cedb01dc0fe73f51ca3e57 to your computer and use it in GitHub Desktop.
Replace by position
## Context: https://twitter.com/grant_mcdermott/status/1249825585175523328
set.seed(123)
m = matrix(1:10000000, ncol = 1000)
x_pos = sample.int(nrow(m), size = nrow(m)/2)
y_pos = sample.int(ncol(m), size = ncol(m)/2)
m_pos = (y_pos-1)*nrow(m) + x_pos
library(data.table)
d = as.data.table(m)
library(microbenchmark)
f1 = function(val) {
m[x_pos, y_pos] = val
}
f2 = function(val) {
replace(m, m_pos, val)
}
f3 = function(val) {
d[x_pos, y_pos] = val
}
microbenchmark(f1("a"), f2("a"), f3("a"), times = 10)
# Unit: milliseconds
# expr min lq mean median uq max neval cld
# f1("a") 1763.69864 1875.60289 2437.56736 2205.15627 2622.15864 4090.56228 10 b
# f2("a") 1713.88150 1861.22836 2167.71451 2139.27080 2264.02732 2870.44860 10 b
# f3("a") 34.73604 35.17439 36.47502 35.31709 36.22141 45.15878 10 a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment