[英]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: 我目前正在使用double(嵌套) for
循环来实现以下公式: . 。
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? (A)输入r
如在本情况下,单个数.3
,而不是矩阵.3
秒和1
S'
(B) Use a lapply
family code eg, mapply
instead of a nested for
-loop? (B)使用lapply
系列代码,例如mapply
而不是嵌套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. outer
将每个元素与每个其他元素相乘,这就是double循环正在做的事情。 We then take sqrt
of all the values, multiply with r
matrix, sum
them and multiply by (1/m)^2
. 然后,我们采取sqrt
所有的值,用乘法r
矩阵, sum
它们并通过乘以(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. 我们想将对角元素乘以1,将其余的元素与r
值相乘,这在r
是矩阵时很容易,但是,如果它是单个数字,则需要相应地构造矩阵。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.