Home > Mobile >  Speeding code up. Loop over sum with kernel function
Speeding code up. Loop over sum with kernel function

Time:11-09

I am running below code to evaluate a function at each value of r.

For each element of r, the function calculates the sum of elements of a matrix product. Before doing this, values of M are adjusted based on a kernel function.

# (1) set-up with toy data 
r <- seq(0, 10, 1)
bw <- 25 
M <- matrix(data = c(0, 1, 2,
                     1, 0, 1,
                     2, 1, 0), nrow = 3, ncol = 3)

X <- matrix(rep(1, 9), 3, 3)
#

# (2) computation 
res <- c()

# loop, calculationg sum, Epanechnikov kernel 
for(i in seq_along(r)) {
  
  res[i] <- sum(
    
    # Epanechnikov kernel
    ifelse(-bw < (M - r[i]) & (M - r[i]) < bw,
           3 * (1 - ((M - r[i])^2 / bw^2)) / (4*bw),
           0) * X,
    na.rm = TRUE
  )
  
}

# result 
res  

I am looking for recommendations to speed this up using base R. Thank you!

CodePudding user response:

Using outer:

Mr <- outer(c(M), r, "-")
colSums(3*(1 - Mr^2/bw^2)/4/bw*(abs(Mr) < bw)*c(X))
#>  [1] 0.269424 0.269760 0.269232 0.267840 0.265584 0.262464 0.258480 0.253632 0.247920 0.241344 0.233904

I'll also note that the original for loop solution can be sped up by pre-allocating res (e.g., res <- numeric(length(r))) prior to the for loop.

  • Related