我在R中有一个应该是对称的矩阵,但是,由于机器精度,矩阵永远不对称(值相差大约10 ^ -16).因为我知道矩阵是对称的,所以到目前为止我一直在这样做以解决这个问题:
s.diag = diag(s)
s[lower.tri(s,diag=T)] = 0
s = s + t(s) + diag(s.diag,S)
Run Code Online (Sandbox Code Playgroud)
有一个更好的一行命令吗?
小智 52
s<-matrix(1:25,5)
s[lower.tri(s)] = t(s)[lower.tri(s)]
Run Code Online (Sandbox Code Playgroud)
Met*_*ics 13
您可以使用R forceSymmetric中的Matrix包中的函数强制矩阵对称:
library(Matrix)
x<-Matrix(rnorm(9), 3)
> x
3 x 3 Matrix of class "dgeMatrix"
[,1] [,2] [,3]
[1,] -1.3484514 -0.4460452 -0.2828216
[2,] 0.7076883 -1.0411563 0.4324291
[3,] -0.4108909 -0.3292247 -0.3076071
A <- forceSymmetric(x)
> A
3 x 3 Matrix of class "dsyMatrix"
[,1] [,2] [,3]
[1,] -1.3484514 -0.4460452 -0.2828216
[2,] -0.4460452 -1.0411563 0.4324291
[3,] -0.2828216 0.4324291 -0.3076071
Run Code Online (Sandbox Code Playgroud)
Pey*_*ton 10
如果值只差异那么多,那么解决方法是否真的有必要?
有人指出我之前的回答是错误的.我更喜欢其他一些,但由于我无法删除这个(由离开的用户接受),这是使用该micEcon包的另一个解决方案:
symMatrix(s[upper.tri(s, TRUE)], nrow=nrow(s), byrow=TRUE)
Run Code Online (Sandbox Code Playgroud)
s<-matrix(1:25,5)
pmean <- function(x,y) (x+y)/2
s[] <- pmean(s, matrix(s, nrow(s), byrow=TRUE))
s
#-------
[,1] [,2] [,3] [,4] [,5]
[1,] 1 4 7 10 13
[2,] 4 7 10 13 16
[3,] 7 10 13 16 19
[4,] 10 13 16 19 22
[5,] 13 16 19 22 25
Run Code Online (Sandbox Code Playgroud)