我正在尝试在R中的矩阵中获取某一行的列总和。但是,我不希望对整行进行求和,而只需要指定数量的列,即在这种情况下,所有列都在对角线上方。我已经尝试了sum和rowSums函数,但它们要么给我奇怪的结果或错误信息。为了说明,请参阅下面的8x8矩阵的示例代码。对于第一行,我需要除项目[1,1]之外的行的总和,对于第二行,除了项目[2,1]和[2,2]等之外的总和。
m1 <- matrix(c(0.2834803,0.6398198,0.0766999,0.0000000,0.0000000,0.0000000,0.0000000,0.0000000,
0.0000000,0.1101746,0.6354086,0.2544168,0.0000000,0.0000000,0.0000000,0.0000000,
0.0000000,0.0000000,0.0548145,0.9451855,0.0000000,0.0000000,0.0000000,0.0000000,
0.0000000,0.0000000,0.0000000,0.3614786,0.6385214,0.0000000,0.0000000,0.0000000,
0.0000000,0.0000000,0.0000000,0.0000000,0.5594658,0.4405342,0.0000000,0.0000000,
0.0000000,0.0000000,0.0000000,0.0000000,0.0000000,0.7490395,0.2509605,0.0000000,
0.0000000,0.0000000,0.0000000,0.0000000,0.0000000,0.0000000,0.5834363,0.4165637,
0.0000000,0.0000000,0.0000000,0.0000000,0.0000000,0.0000000,0.0000000,1.0000000),
8, 8, byrow = TRUE,
dimnames = list(c("iAAA", "iAA", "iA", "iBBB", "iBB", "iB", "iCCC", "iD"),
c("iAAA_p", "iAA_p", "iA_p", "iBBB_p", "iBB_p", "iB_p", "iCCC_p", "iD_p")))
我尝试了以下内容:
rowSums(m1[1, 2:8]) --> Error in rowSums(m1[1, 2:8]) :
'x' must be an array of at least two dimensions
可替换地:
sum(m1[1,2]:m1[1,8]) --> wrong result of 0.6398198 (which is item [1,2])
据我所知,rowSums需要一个数组而不是一个向量(虽然不确定为什么)。但我不明白为什么使用sum的第二种方法不起作用。理想情况下,有一些方法只能对位于对角线上方的所有列进行求和。
非常感谢!
答案 0 :(得分:5)
问题是你没有将数组传递给rowSums
:
class(m1[1,2:8])
# [1] "numeric"
这是一个数字向量。使用多行,它可以正常工作:
class(m1[1:2,2:8])
# [1] "matrix"
rowSums(m1[1:2,2:8])
# iAAA iAA
#0.7165197 1.0000000
如果要对位于对角线上方的所有列求和,则可以使用lower.tri
将对角线下方的所有元素设置为0
(或者可能是NA
)然后使用rowSums
。如果您不想包含对角元素本身,可以设置diag = TRUE
(感谢@Fabio指出这一点):
m1[lower.tri(m1 , diag = TRUE)] <- 0
rowSums(m1)
# iAAA iAA iA iBBB iBB iB iCCC iD
#0.7165197 0.8898254 0.9451855 0.6385214 0.4405342 0.2509605 0.4165637 0.0000000
# With 'NA'
m1[lower.tri(m1)] <- NA
rowSums(m1,na.rm=T)
# iAAA iAA iA iBBB iBB iB iCCC iD
#0.7165197 0.8898254 0.9451855 0.6385214 0.4405342 0.2509605 0.4165637 0.0000000