Skip to content

consecutive numbering of elements in a matrix

2 messages · Jim Bouldin, Dimitris Rizopoulos

#
OK I see it now--thanks.  I was interpreting the apply function incorrectly
in terms of what it was summing.
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:
[,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
#
one approach is the following:

B <- cbind(c(1:6, NA), c(1:3, NA,NA,NA, 4), c(1:3, NA,NA, 4,5))
matrix(B[order(col(B), B)], nrow(B), ncol(B))


I hope it helps.

Best,
Dimitris
Jim Bouldin wrote: