rowsum for matrix over specified number of columns in R

旧时模样 提交于 2019-12-04 11:11:41

The problem is you are not passing an array to rowSums:

class(m1[1,2:8])
# [1] "numeric"

This is a numeric vector. Use more than a single row and it will work just fine:

class(m1[1:2,2:8])
# [1] "matrix"

rowSums(m1[1:2,2:8])
#     iAAA       iAA 
#0.7165197 1.0000000 

If you want to sum all the columns that lie above the diagonal then you can use lower.tri to set all elements below the diagonal to 0 (or perhaps NA) and then use rowSums. If you do not want to include the diagonal elements themselves you can set diag = TRUE (thanks to @Fabio for pointing this out):

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 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!