我正在使用的矩阵看起来像这样。它是正方形
structure(c(3, 4, 2, 4, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0,
0, 0, 0, 2, 2, 0, 3, 9), .Dim = c(5L, 5L), .Dimnames = list(c("a1",
"a2", "a3", "a4", "a5"), c("a1", "a2", "a3", "a4", "a5")))
我需要将三角形下方和上方的元素相加,并清空矩阵的上三角形。结果看起来像这样
structure(c(3, 4, 2, 4, 2, 0, 0, 3, 0, 2, 0, 0, 0, 0, 0, 0, 0,
0, 0, 3, 0, 0, 0, 0, 9), .Dim = c(5L, 5L), .Dimnames = list(c("a1",
"a2", "a3", "a4", "a5"), c("a1", "a2", "a3", "a4", "a5")))
有一种有效的方法吗?因此,只需在元素的下半部分添加上半部分的值 -
答案 0 :(得分:0)
我们可以尝试
m1[lower.tri(m1)] <- m1[lower.tri(m1)] + t(m1)[lower.tri(m1)]
m1[upper.tri(m1)] <- 0
identical(m1, m2)
#[1] TRUE