I want to use sapply() to conduct some basic calculations:
N <- 10000
idx <- sample(1:N, N, replace = TRUE)
sapply(1:N, function(j) {sum(idx == j)})
N <- 10000
idx <- sample(1:N, N, replace = TRUE)
vec <- rnorm(1:N)
sapply(1:nc, function(j) {sum(vec[idx == j])})
However, these are very slow when I put them within loop (I don't know why). For example:
B <- 100
N <- 10000
for (b in 1:B) {
idx <- sample(1:N, N, replace = TRUE)
vec <- rnorm(1:N)
tmp <- sapply(1:N, function(j) {sum(vec[idx == j])})
}
I would like to ask if there is any way to make this faster?
Here are options for your first and second code blocks, respectively
tabulate(idx, nbins = N)
and
tapply(vec, factor(idx, levels = 1:N), sum, default = 0L)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With