考虑通用矩阵nxn - 例如:
Syntax error or access violation: 1067 Invalid default value for 'date'
如何计算“右下方”三角形中的行总和并在向量中显示信息?
答案 0 :(得分:6)
找一个封装所需数据的掩码:
> mask <- apply(lower.tri(A, diag = FALSE), 1, rev)
> mask
[,1] [,2] [,3] [,4]
[1,] FALSE FALSE FALSE FALSE
[2,] FALSE FALSE FALSE TRUE
[3,] FALSE FALSE TRUE TRUE
[4,] FALSE TRUE TRUE TRUE
将此蒙版相乘并计算总和:
> A * mask
[,1] [,2] [,3] [,4]
[1,] 0 0 0 0
[2,] 0 0 0 14
[3,] 0 0 11 15
[4,] 0 8 12 16
> rowSums(A * mask)
[1] 0 14 26 36
答案 1 :(得分:2)
A = matrix(1:16, 4)
A
# [,1] [,2] [,3] [,4]
# [1,] 1 5 9 13
# [2,] 2 6 10 14
# [3,] 3 7 11 15
# [4,] 4 8 12 16
sapply(1:NROW(A), function(i) sum(tail(A[i,], i - 1)))
#[1] 0 14 26 36
答案 2 :(得分:1)
这是一个解决方案。关键是使用lower.tri
或upper.tri
函数,然后使用apply
对每行或每列进行排序。最后计算每一行的总和。
# Create example data frame
m <- matrix(1:16, 4)
m
# [,1] [,2] [,3] [,4]
# [1,] 1 5 9 13
# [2,] 2 6 10 14
# [3,] 3 7 11 15
# [4,] 4 8 12 16
# Calculate the sum
rowSums(m * apply(lower.tri(m), 1, sort))
# [1] 0 14 26 36
rowSums(m * apply(upper.tri(m), 2, sort))
# [1] 0 14 26 36