簡體   English   中英

按行順序替換上三角矩陣元素

[英]Replacing upper triangular matrix elements in row order

我有一個如下的方陣。

> ex_mat
          [,1]      [,2]      [,3]      [,4]
[1,] 0.4270634 2.1920890 0.5647472 1.7149861
[2,] 2.0556220 1.1157322 2.6723637 0.3155507
[3,] 1.2252602 0.1063053 0.6396099 0.7903348
[4,] 0.3614062 1.1118661 0.5000143 0.2491543

我已經按行順序(從最大到最小)對矩陣的上非對角線部分進行了排名。

> rank(-(t(ex_mat)[lower.tri(ex_mat)]))
[1] 2 5 3 1 6 4

我想用上面獲得的等級替換“ex_mat”的上部非對角線元素。 我使用https://statisticsglobe.com/modify-diagonal-lower-upper-triangular-part-matrix-r作為示例代碼。 雖然我的排名是正確的,但代碼似乎是按列順序插入排名。

> ex_mat_new <- ex_mat
> ex_mat_new[upper.tri(ex_mat_new)] <- rank(-(t(ex_mat)[lower.tri(ex_mat)]))
> ex_mat_new
          [,1]      [,2]      [,3]      [,4]
[1,] 0.4270634 2.0000000 5.0000000 1.0000000
[2,] 2.0556220 1.1157322 3.0000000 6.0000000
[3,] 1.2252602 0.1063053 0.6396099 4.0000000
[4,] 0.3614062 1.1118661 0.5000143 0.2491543

我怎樣才能解決這個問題? [1,4] 和 [2,3] 關閉。 謝謝你。

值插入按列順序(在矩陣、data.frame 中)。 我們可以在lower.tri上賦值,然后得到t

ex_mat_new[lower.tri(ex_mat_new)] <- rank(-(t(ex_mat)[lower.tri(ex_mat)]))
ex_mat_new <- t(ex_mat_new)
ex_mat_new[lower.tri(ex_mat_new)] <- ex_mat[lower.tri(ex_mat)]

-輸出

> ex_mat_new
          [,1]      [,2]      [,3]      [,4]
[1,] 0.4270634 2.0000000 5.0000000 3.0000000
[2,] 2.0556220 1.1157322 1.0000000 6.0000000
[3,] 1.2252602 0.1063053 0.6396099 4.0000000
[4,] 0.3614062 1.1118661 0.5000143 0.2491543

或者這可以用replace在一行中完成

t(replace(t(ex_mat), lower.tri(ex_mat), rank(-(t(ex_mat)[lower.tri(ex_mat)]))))

-輸出

       [,1]      [,2]      [,3]      [,4]
[1,] 0.4270634 2.0000000 5.0000000 3.0000000
[2,] 2.0556220 1.1157322 1.0000000 6.0000000
[3,] 1.2252602 0.1063053 0.6396099 4.0000000
[4,] 0.3614062 1.1118661 0.5000143 0.2491543

數據

ex_mat <- structure(c(0.4270634, 2.055622, 1.2252602, 0.3614062, 2.192089, 
1.1157322, 0.1063053, 1.1118661, 0.5647472, 2.6723637, 0.6396099, 
0.5000143, 1.7149861, 0.3155507, 0.7903348, 0.2491543), .Dim = c(4L, 
4L), .Dimnames = list(NULL, NULL))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM