gpt4 book ai didi

R 中指定列数上矩阵的 rowsum

转载 作者:行者123 更新时间:2023-12-03 21:39:20 24 4
gpt4 key购买 nike

我正在尝试获取 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 的第二种方法不起作用。理想情况下,有一些方法可以只对位于对角线上方的一行中的所有列求和。

非常感谢!

最佳答案

问题是您没有将数组传递给 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

关于R 中指定列数上矩阵的 rowsum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17293999/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com