Skip to content
Prev 201104 / 398503 Next

consecutive numbering of elements in a matrix

On Nov 21, 2009, at 3:25 PM, William Dunlap wrote:

            
mtx <- matrix(scan(textConnection(" 1   NA   NA
     3   NA   NA
     3   10   17
     4   12   18
     6   16   19
     6   22   20
     5   11   NA"), byrow=TRUE, ncol=3)
Semms like a simple apply would be sufficient:

apply(mtx, 2, function(x) cumsum(!is.na(x)))

      [,1] [,2] [,3]
[1,]    1    0    0
[2,]    2    0    0
[3,]    3    1    1
[4,]    4    2    2
[5,]    5    3    3
[6,]    6    4    4
[7,]    7    5    4

Or if NA's are needed in the original NA positions:

 > mt2 <- apply(mtx, 2, function(x) cumsum(!is.na(x)))
 > is.na(mt2) <- is.na(mtx)
 > mt2
      [,1] [,2] [,3]
[1,]    1   NA   NA
[2,]    2   NA   NA
[3,]    3    1    1
[4,]    4    2    2
[5,]    5    3    3
[6,]    6    4    4
[7,]    7    5   NA
David Winsemius, MD
Heritage Laboratories
West Hartford, CT