简体   繁体   English

循环通过R中的矩阵

[英]loop though a matrix in R

I try to loop trough a matrix but cant find a easy and elegant way instead of writing many (>10) equations... Can anyone help me please?我尝试通过矩阵循环,但找不到一种简单而优雅的方法,而不是编写许多(> 10)方程......有人可以帮我吗?

My Matrix looks like this:我的矩阵看起来像这样:

在此处输入图像描述

and I want to calculate the following:我想计算以下内容:

(0 * 0 * 4/24) + (0 * 1 * 6/24) + (0 * 2 * 3/24) + (1 * 0 * 3/24) + (1 * 1 * 4/24) + (1 * 2 * 4/24) (0 * 0 * 4/24) + (0 * 1 * 6/24) + (0 * 2 * 3/24) + (1 * 0 * 3/24) + (1 * 1 * 4/24) + (1 * 2 * 4/24)

instead of using而不是使用

__ btw: my code for the matrix __ 顺便说一句:我的矩阵代码

vals<- c(4/24, 6/24, 3/24, 3/24, 4/24, 4/24)
x <- c(0,1)
y <- c(0,1,2)
df <- matrix(vals, byrow = TRUE, nrow = 2, ncol = 3,
             dimnames = list(x,y))

instead of calculation each step manually, I think there should be a for-loop method, but cant figure it out..而不是手动计算每个步骤,我认为应该有一个for循环方法,但无法弄清楚..

A possible solution:一个可能的解决方案:

c(x %*% df %*% y) 

#> [1] 0.5

Another possible solution, based on outer :另一种可能的解决方案,基于outer

sum(outer(x, y, Vectorize(\(x,y) x*y*df[x+1,y+1])))

#> [1] 0.5
x <- c(0, 1)
y <- c(0, 1, 2)
vals<- c(4/24, 6/24, 3/24, 3/24, 4/24, 4/24)
mat <- matrix(vals, byrow = TRUE, nrow = 2, ncol = 3,
              dimnames = list(x,y))  ## not a data frame; don't call it "df"

There is even a better way than a for loop:还有比for循环更好的方法:

sum(tcrossprod(x, y) * mat)
#[1] 0.5
sum((x %o% y) * df)

Explanation:解释:

x %o% y gets the outer product of vectors x and y which is: x %o% y得到向量xy的外积,即:

#>      [,1] [,2] [,3]
#> [1,]    0    0    0
#> [2,]    0    1    2

Since that has the same dimensions as df , you can multiply the corresponding elements and get the sum: sum((x %o% y) * df)由于它与df具有相同的维度,因此您可以将相应的元素相乘并得到总和: sum((x %o% y) * df)

If you are new to R (as I am), here is the loop approach.如果您是 R 新手(就像我一样),这里是循环方法。

result = 0
for (i in 1:length(x)) {
  for (j in 1:length(y)) {
    result = result + x[i] * y[j] * df[i, j]
  }
}
result

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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