简体   繁体   中英

R - Returning colSums of pairwise selected rows from matrix

Sorry if this question was already asked somewhere, but a search didn't really help me. First of all, I'm a real beginner at programming and I'm stuck trying to calculate what probably is, something basic...

Basically what I have is a 14x265 matrix filled with 0's and 1's. For this matrix I want to calculate and return the colSums for all pairwise selected rows.

For example Let's take the matrix

1 0 1 0    
0 1 1 1
0 0 0 1

I would like the following returned to me (matrix 3x5):

1-2 1 1 2 1    
1-3 1 0 1 1
2-3 0 1 1 2

I have absolutely no idea how to do this. I was working with the 'combn' and 'apply' functions, but that was unsuccessful so far.

Can anybody help me?

Thanks in advance! Nick

With your sample matrix

mm<-structure(c(1L, 0L, 0L, 0L, 1L, 0L, 1L, 1L, 0L, 0L, 1L, 1L), .Dim = 3:4)

You can use apply()

t(apply(combn(nrow(mm),2),2, function(i) {
    colSums(mm[i,])
}))

     [,1] [,2] [,3] [,4]
[1,]    1    1    2    1
[2,]    1    0    1    1
[3,]    0    1    1    2

And if you wanted to add in the labels

cx <- combn(nrow(mm),2)
data.frame(
    pair=apply(cx,2, paste, collapse="-"),
    t(apply(cx,2, function(i) {
        colSums(mm[i,])
    }))
 )
#   pair X1 X2 X3 X4
# 1  1-2  1  1  2  1
# 2  1-3  1  0  1  1
# 3  2-3  0  1  1  2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM