[R] consecutive numbering of elements in a matrix
Dimitris Rizopoulos
d.rizopoulos at erasmusmc.nl
Sun Nov 22 20:00:27 CET 2009
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:
>> 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
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
--
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center
Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014
More information about the R-help
mailing list