rnorouzian
rnorouzian

Reputation: 7517

Replacing a double nested for-loop with a lapply family in R

I'm currently using a double (nested) for loop to implement the below formula:enter image description here.

Everything works great. But I was wondering if I could:

(A) Input r as a single number in this case .3 instead of a matrix of .3s and 1s?

(B) Use a lapply family code e.g., mapply instead of a nested for-loop?

V <- c(.25, .5, .75) 
m <- length(V)

r <- matrix(c(1, .3, .3, .3, 1, .3, .3,.3, 1), 3, 3)

sumV <- 0 

for (i in 1:nrow(r)) {
  for (j in 1:nrow(r)) {
    sumV <- sumV + r[i,j] * sqrt(V[[i]]*V[[j]])
     }
   } 

(1/m)^2 * sumV # Final answer

Upvotes: 1

Views: 179

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389275

A short version of your attempt is

(1/m)^2 * sum(sqrt(outer(V, V)) * r)
#[1] 0.2599292

outer multiplies every element with every other element which is what double loop is doing. We then take sqrt of all the values, multiply with r matrix, sum them and multiply by (1/m)^2.


We want to multiply the diagonal elements with 1 and rest of them with r value which is easy when r is a matrix however, if it is a single number we need to construct the matrix accordingly.

r <- .3
mat <- sqrt(outer(V, V))
mult_matrix <- matrix(r, ncol(mat), nrow(mat))
diag(mult_matrix) <- 1
(1/m)^2 * sum(mat * mult_matrix)
#[1] 0.2599292

Upvotes: 2

Related Questions