I want to use sapply()
to conduct some basic calculations:
- 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)})
- 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:nc, function(j) {sum(vec[idx == j])})
}
I would like to ask if there is any way to make this faster?