[R] consecutive numbering of elements in a matrix

Jim Bouldin jrbouldin at ucdavis.edu
Sun Nov 22 19:31:43 CET 2009


> And think about the fact that row(A) and apply(is.na(A), 2, cumsum)  
> will be identical in the case where there are no NAs, so their  
> difference would be a zero matrix. Double negativism strikes again....  
> not(is.na) == "is"

OK I see it now--thanks.  I was interpreting the apply function incorrectly
in terms of what it was summing.

> You cannot have unequal length columns in a matrix. Only a list is  
> able to handle that task. So we need a more clear description of what  
> you expect, preferably typed out in full so we can "see" it.

Given a matrix B like before, which has NAs mixed with integers in all
columns, where those NAs may occur anywhere within the columns, and where
the integers within a column are always consecutive and increasing: 

> B
     [,1] [,2] [,3] ...etc
[1,]    1    1    1
[2,]    2    2    2
[3,]    3    3    3
[4,]    4   NA   NA
[5,]    5   NA   NA
[6,]    6   NA    4
[7,]    NA   4    5
etc

I would like to create a new matrix, in which all NAs that occur BETWEEN
consecutive integers are removed, and the integers which follow such NAs
are moved "up" in the column to replace them.  NAs which occur near the
bottom of each column, and are NOT followed by more integers can be
retained without problem.  Empty spaces that might result from this
process, near the column bottoms as the integers are moved up, would need
to be replaced by NAs so that equal numbers of entries are maintained in
each row, hence still allowing a matrix to exist:

If B above were in fact the complete matrix, the desired result would thus be:

     [,1] [,2] [,3] etc
[1,]    1    1    1
[2,]    2    2    2
[3,]    3    3    3
[4,]    4    4    4
[5,]    5   NA    5
[6,]    6   NA   NA
[7,]    NA  NA   NA
etc

In other words, all integers of a particular value in the original matrix
need to be placed on the same row of a new matrix, and all "empty" values
replaced with NA.  I hope that explains it well enough, but will try again
if not. Thanks again for any help.
Jim




More information about the R-help mailing list