我有以下矩阵/数据帧:
> e
V1 V2 V3 V4 V5
1 0 2 3 4 5
2 0 0 6 8 10
3 0 0 0 12 15
4 0 0 0 0 20
5 0 0 0 0 0
Run Code Online (Sandbox Code Playgroud)
在这种情况下,N = 5(行数=列数).我想填写这个对称矩阵中的缺失值(e [1,2] = e [2,1]等).有没有一种最有效的方法来填补缺失的值(N在我的情况下矩阵大小相当大)?有没有比嵌套循环更好的方法?
为了完成,我还想展示这种技术.如果矩阵的下半部分(在对角线下)填充了值,则添加转置将不起作用,因为它将它们添加到矩阵的上部.
使用Matrix包我们可以创建一个稀疏矩阵,在创建一个大矩阵的对称的情况下,需要更少的内存,甚至加快它.
为了从矩阵创建对称稀疏矩阵,e
我们会这样做:
library(Matrix)
rowscols <- which(upper.tri(e), arr.ind=TRUE)
sparseMatrix(i=rowscols[,1], #rows to fill in
j=rowscols[,2], #cols to fill in
x=e[upper.tri(e)], #values to use (i.e. the upper values of e)
symmetric=TRUE, #make it symmetric
dims=c(nrow(e),nrow(e))) #dimensions
Run Code Online (Sandbox Code Playgroud)
输出:
5 x 5 sparse Matrix of class "dsCMatrix"
[1,] . 2 3 4 5
[2,] 2 . 6 8 10
[3,] 3 6 . 12 15
[4,] 4 8 12 . 20
[5,] 5 10 15 20 .
Run Code Online (Sandbox Code Playgroud)
微基准测试:
让我们创建一个函数来从矩阵中生成对称矩阵(默认情况下将矩阵的上半部分复制到下面):
symmetrise <- function(mat){
rowscols <- which(upper.tri(mat), arr.ind=TRUE)
sparseMatrix(i=rowscols[,1],
j=rowscols[,2],
x=mat[upper.tri(mat)],
symmetric=TRUE,
dims=c(nrow(mat),ncol(mat)) )
}
Run Code Online (Sandbox Code Playgroud)
并测试:
> microbenchmark(
e + t(e),
symmetrise(e),
e[lower.tri(e)] <- t(e)[lower.tri(e)],
times=1000
)
Unit: microseconds
expr min lq mean median uq max neval cld
e + t(e) 75.946 99.038 117.1984 110.841 134.9590 246.825 1000 a
symmetrise(e) 5530.212 6246.569 6950.7681 6921.873 7034.2525 48662.989 1000 c
e[lower.tri(e)] <- t(e)[lower.tri(e)] 261.193 322.771 430.4479 349.968 395.3815 36873.894 1000 b
Run Code Online (Sandbox Code Playgroud)
正如你所看到symmetrise
的实际上要慢得多e + t(e)
,df[lower.tri(df)] <- t(df)[lower.tri(df)]
但至少你有一个自动对称矩阵的函数(默认情况下取上部并创建下部)如果你有一个大矩阵,内存是个问题,这可能派上用场吧.
PS无论你.
在Matrix中看到哪一个,这都代表零.通过使用不同的系统,稀疏矩阵是一种"压缩"对象,使其具有更高的内存效率.
另外还有速度:
2*symmpart(as.matrix(e))
Run Code Online (Sandbox Code Playgroud)
这是一个基准:
Unit: microseconds
expr min lq mean median uq max neval
e + t(e) 572.505 597.194 655.132028 611.5420 628.4860 8424.902 1000
symmetrise(e) 1128.220 1154.562 1215.740071 1167.0020 1185.6585 10656.059 1000
e[lower.tri(e)] <- e[upper.tri(e, FALSE)] 285.013 311.191 350.846885 327.1335 339.5910 8106.006 1000
2 * symmpart(as.matrix(e)) 78.392 93.953 101.330522 102.1860 107.9215 153.628 1000
Run Code Online (Sandbox Code Playgroud)
它可以获得这种速度,因为它可以直接创建对称矩阵.
df[lower.tri(df)] <- t(df)[lower.tri(df)]
Run Code Online (Sandbox Code Playgroud)
输出:
V1 V2 V3 V4 V5
1 0 2 3 4 5
2 2 0 6 8 10
3 3 6 0 12 15
4 4 8 12 0 20
5 5 10 15 20 0
Run Code Online (Sandbox Code Playgroud)
数据:
df <- structure(list(V1 = c(0L, 0L, 0L, 0L, 0L), V2 = c(2L, 0L, 0L,
0L, 0L), V3 = c(3L, 6L, 0L, 0L, 0L), V4 = c(4L, 8L, 12L, 0L,
0L), V5 = c(5L, 10L, 15L, 20L, 0L)), .Names = c("V1", "V2", "V3",
"V4", "V5"), class = "data.frame", row.names = c("1", "2", "3",
"4", "5"))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3609 次 |
最近记录: |