英文:
Matrix/array multiplication in R data frame
问题
我尝试从R中的数据框执行矩阵乘法。
乘法的方式是,第一个数组是数据框中每一列的所有元素(1x6)。然后,我们将其与相关矩阵(6x6)相乘,再与第一个数组的转置(6x1)相乘,以得到最终结果。这必须在数据框的所有行上执行。
以下是如何在Excel中执行此操作的图像。
snapshot of calculation in excel
A <- c(2,3,4,5,6)
B <- c(4,5,6,7,8)
C <- c(6,7,8,9,10)
D <- c(8,9,10,11,12)
E <- c(10,11,12,13,14)
F <- c(12,13,14,15,16)
df <- data.frame(A, B, C, D, E, F)
## 6x6相关矩阵
corr <- matrix(
c(1,0,0,0,0,0,
0,1,0,0,0,0,
0,0,1,0.6,0.6,0.5,
0,0,0.6,1,0.6,0.7,
0,0,0.6,0.6,1,0.6,
0,0,0.5,0.7,0.6,1),
nrow = 6, ncol = 6, byrow = TRUE)
我需要在数据框中添加另一列,以得到第1行的结果 = [2,4,6,8,10,12] * corr * 转置[2,4,6,8,10,12]。
英文:
I am trying to to do a matrix multiplication from a data frame in R.
The multiplication is such a way that 1st array is all elements from each column from data frame (1x6). Then we multiply it with a correlation matrix (6x6) and again with a transpose of 1st array (6x1) to give a final result. This has to be done on all rows of a data frame
here is the image of how i do it in excel
snapshot of calculation in excel
A <- c(2,3,4,5,6)
B <- c(4,5,6,7,8)
C <- c(6,7,8,9,10)
D <- c(8,9,10,11,12)
E <- c(10,11,12,13,14)
F <- c(12,13,14,15,16)
df <- data.frame (A,B,C,D,E,F)
## 6x6 correlation matrix
corr <- matrix(
c(1,0,0,0,0,0,
0,1,0,0,0,0,
0,0,1,.6,.6,.5,
0,0,.6,1,.6,.7,
0,0,.6,.6,1,.6,
0,0,.5,.7,.6,1),
nrow = 6,ncol =6, byrow = TRUE)
What i need is to add another col in df with result for row 1 = [2,4,6,8,10,12]* corr * transpose[2,4,6,8,10,12]
答案1
得分: 2
以下是翻译好的部分:
以下的一行代码解决了这个问题。
请注意,在 R 中,向量是列向量,所以转置在乘法的左侧。
apply(df, 1, \(x) t(x) %*% corr %*% x)
#> [1] 940.0 1167.2 1420.8 1700.8 2007.2
创建于2023年02月18日,使用 reprex v2.0.2。
英文:
The following one-liner solves it.
Note that in R vectors are column vectors so the transpose is on the left side of the multiplication.
apply(df, 1, \(x) t(x) %*% corr %*% x)
#> [1] 940.0 1167.2 1420.8 1700.8 2007.2
<sup>Created on 2023-02-18 with reprex v2.0.2</sup>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论