[R] number of pairwise present data in matrix with missings

Gabor Grothendieck ggrothendieck at myway.com
Tue Nov 23 15:06:12 CET 2004


Andreas Wolf <andreas.wolf <at> uni-jena.de> writes:

: 
: is there a smart way of determining the number of pairwise present data
: in a data matrix with missings (maybe as a by-product of some
: statistical function?)
: 
: so far, i used several loops like:
: 
: for (column1 in 1:99) {
:   for (column2 in 2:100) {
:     for (row in 1:500) {
:       if (!is.na(matrix[row,column1]) & !is.na(matrix[row,column2])) {
:         pairs[col1,col2] <- pairs[col1,col2]+1
:       }
:     }
:   }
: }
: 
: but this seems neither the most elegant nor an utterly fast solution.

This is just matrix multiplication of the !na(x) matrix:

R> x <- matrix(1:12,4,3)
R> x[c(1,10)] <- NA
R> x
     [,1] [,2] [,3]
[1,]   NA    5    9
[2,]    2    6   NA
[3,]    3    7   11
[4,]    4    8   12
R> crossprod(!is.na(x))
     [,1] [,2] [,3]
[1,]    3    3    2
[2,]    3    4    3
[3,]    2    3    3




More information about the R-help mailing list