[R] consecutive numbering of elements in a matrix

Jim Bouldin jrbouldin at ucdavis.edu
Sun Nov 22 17:11:43 CET 2009


Many thanks to Dimitris, William and David for very helpful answers which
solved my problem.  Being a relatve newb, I am confused by something in the
solutions by Dimitris and David.

#Create a matrix A as follows:

> A <- matrix(sample(50, 21), 7, 3)
> A[sample(21, 5)] <- NA;A

     [,1] [,2] [,3]
[1,]   36   38   24
[2,]    6   33   13
[3,]   12   42   10
[4,]    7   NA   NA
[5,]   48   NA   NA
[6,]    3   NA   47
[7,]   29   23    4

> B = row(A) - apply(is.na(A), 2, cumsum);B

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

#But:

> B = row(A) - apply(!is.na(A), 2, cumsum);B
     [,1] [,2] [,3]
[1,]    0    0    0
[2,]    0    0    0
[3,]    0    0    0
[4,]    0    1    1
[5,]    0    2    2
[6,]    0    3    2
[7,]    0    3    2

This seems exactly backwards to me.  The is.na(A) command should be
cumulatively summing the NA values and !is.na(A) should be doing so on the
non-NA values.  But the opposite is the case.  I'm glad I have a solution
but this apparent backwardness of expected logic has me worried.

I do have another, tougher question if anyone has the time, which is, given
a resulting matrix like B below:

> is.na(B) <- is.na(A);B

     [,1] [,2] [,3]
[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,]    7    4    5

how can I rearrange all the columns so that equal values are in the same
row, i.e. in the case above, the NA values are removed from columns 2 and 3
and all non-NA values that had been below them are moved up to replace them.

Thanks again for your help.

Jim




More information about the R-help mailing list