Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faster way to implement sapply()

I want to use sapply() to conduct some basic calculations:

  1. Calculate the number of times that a value appears in a bootstrap sample
N <- 10000
idx <- sample(1:N, N, replace = TRUE)
sapply(1:N, function(j) {sum(idx == j)})
  1. Calculate the sum of one vector corresponding to the index from a bootstrap sample
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?

like image 946
wut Avatar asked Jul 12 '26 18:07

wut


1 Answers

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)
like image 158
ThomasIsCoding Avatar answered Jul 15 '26 08:07

ThomasIsCoding