Shayan Abbasi
Shayan Abbasi

Reputation: 374

How to convert a loop which is dependent on index, to apply() to improve speed in R?

My loop looks like this:

my.loglik.cv <- function(Y,h){
L_h <- 0
for(i in 1:length(Y)){
L_h<-L_h+log(my.kernel.density.estimator(Y[i],Y[-i],h))}
return(L_h)
}

as you see, it is important to me to subset Y by [-i], but I need to use apply family to improve the performance. Any solution?

Thanks

Upvotes: 0

Views: 40

Answers (1)

dcarlson
dcarlson

Reputation: 11056

This will not necessarily be faster, but it is worth a try:

L_h <- sum(sapply(1:length(Y), function(i) log(my.kernel.density.estimator(Y[i], Y[-i], h))))

Upvotes: 1

Related Questions