R语言 如何在忽略缺失值的情况下用矩阵的转置值进行乘法
在这篇文章中,我们将讨论如何在R编程语言中忽略缺失值的情况下将矩阵乘以其转置。这可以通过将矩阵中的所有缺失值替换为0来实现。
值的替换,可以在O(n*m)中进行,其中n是行的数量,m是列的数量。用0替换并不影响乘积,因此,这是一个有效的解决方案。然后可以用t(matrix)来计算转置。乘积可以通过R中的以下语法来计算。
m1 %*% m2 , where m1 and m2 are the matrices involved.
如果m1是nm维度的矩阵,m2是mn维度的矩阵(因为是转置),得到的乘积矩阵是n*n的方形矩阵。
例1 :
# declaring matrix
mat = matrix(c(1, NA, 2, 3, NA, 4), ncol = 2)
# replacing matrix NA with 0s
mat[is.na(mat)] = 0
# printing original matrix
print ("Original Matrix")
print (mat)
# calculating transpose of the
# matrix
transmat = t(mat)
print ("Transpose Matrix")
print (transmat)
# calculating product of matrices
prod = mat%*%transmat
print ("Product Matrix")
print (prod)
输出
[1] "Original Matrix"
[,1] [,2]
[1,] 1 3
[2,] 0 0
[3,] 2 4
[1] "Transpose Matrix"
[,1] [,2] [,3]
[1,] 1 0 2
[2,] 3 0 4
[1] "Product Matrix"
[,1] [,2] [,3]
[1,] 10 0 14
[2,] 0 0 0
[3,] 14 0 20
原始矩阵的尺寸为3×2,转置的尺寸为2×3。将缺失的数值替换为0,然后将两者相乘,我们得到相当于3×3的方阵的乘积矩阵。
例2: 原矩阵的尺寸为1×3,转置的尺寸为3×1。将缺失的值替换为0,然后将两者相乘,我们得到相当于1×1方阵的乘积矩阵,这基本上是一个奇异单元矩阵。
# declaring matrix
mat = matrix(c(10, NA, 7), ncol = 3)
# replacing matrix NA with 0s
mat[is.na(mat)] = 0
# printing original matrix
print ("Original Matrix")
print (mat)
# calculating transpose of the
# matrix
transmat = t(mat)
print ("Transpose Matrix")
print (transmat)
# calculating product of matrices
prod = mat%*%transmat
print ("Product Matrix")
print (prod)
输出
[1] "Original Matrix"
[,1] [,2] [,3]
[1,] 10 0 7
[1] "Transpose Matrix"
[,1]
[1,] 10
[2,] 0
[3,] 7
[1] "Product Matrix"
[,1]
[1,] 149