简体   繁体   中英

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: 在此处输入图片说明 .

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 .3 s and 1 s?

(B) Use a lapply family code eg, 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM