Rowsum for a matrix by a given number of columns in R

I am trying to get the sum of columns in a matrix in R for a specific row. However, I do not want the whole row to be summed, but only a certain number of columns, that is, in this case, the entire column above the diagonal. I tried the sum and rowSums functions, but they either give me weird results or an error message. See the sample code for an 8x8 matrix below for an illustration. For the first line, I need the sum of the line, except for the element [1,1], for the second line, the sum, except for points [2,1] and [2,2], etc.

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"))) 

I tried the following:

 rowSums(m1[1, 2:8]) --> Error in rowSums(m1[1, 2:8]) : 'x' must be an array of at least two dimensions 

As an alternative:

 sum(m1[1,2]:m1[1,8]) --> wrong result of 0.6398198 (which is item [1,2]) 

As I understand it, rowSums needs an array, not a vector (although I'm not sure why). But I do not understand why the second way of using the sum does not work. Ideally, there is a way to only sum all the columns in a row above the diagonal.

Thanks a lot!

+4
source share
1 answer

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

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

This is a numerical vector. Use more than one line and it will work 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 above the diagonal, you can use lower.tri to set all the elements under the diagonal to 0 (or possibly NA ), and then use rowSums . If you don't want to include the diagonal elements themselves, you can set diag = TRUE (thanks @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 
+5
source

Source: https://habr.com/ru/post/1488036/


All Articles