Your code can be completely redesigned with 3 nested sapply calls. It may be a little difficult to read for the unprepared eye, but the gist of it is that instead of adding one value at a time to sum1[h] , we calculate all the terms created by the innermost loop at a time and sum them up.
Although this vectorized solution is faster than your triplex for loop, the improvement is not dramatic. If you plan to use it many times, I suggest you implement it in C or Fortran (with regular for loops), which greatly improves speed. Beware, however, that it has high temporal complexity and will deteriorate greatly with increased lambda values, ultimately reaching the point where it is impossible to calculate in a reasonable amount of time, regardless of implementation.
lambda <- 2 + 1:200/12.5 sum1 <- sapply(lambda, function(l){ N <- ceiling(l*max(x)) sum(sapply(0:N, function(j){ wj <- (sum(x <= (j+1)/l) - sum(x <= j/l))/100 sum(sapply(0:N, function(k){ constjk <- dbinom(k, j + k, 0.5) wk <- (sum(x <= (k+1)/l) - sum(x <= k/l))/100 l/2*constjk*wk*wj })) })) })
Btw, you donβt need to predefine variables like h , j , k , wj and wk . Moreover, not during vectorization, since assigning them inside functions passed to sapply will create superimposed local variables with the same name (i.e., ignoring those that you predetermined).
Backlin
source share