[R] algorithm to merge same entries in a matrix

Martin Batholdy batholdy at googlemail.com
Tue Aug 30 18:58:47 CEST 2011


Hi,

I have the following, rather unorthodox problem:


I have a matrix that looks like this:

m1 <- matrix(c('a','b','d',NA,'c','c'), 2,3, byrow=TRUE)


        [,1] [,2] [,3]
[1,]  "a"  "b"  "d" 
[2,] NA   "c"  "c" 


now I would like to transform this matrix into this matrix:

        [,1] [,2] [,3] [,4]
[1,]  "a"  "b"  "c"  "d" 
[2,] NA NA NA NA


so the rule is:

if I find the same value (above: 'c') in neighbored cells (here: row wise) put this value in row 1 in a new column between
column of neighbor a and column of neighbor b.





too make it even more complicated:
the definition of neighbored cells is not exclusively row wise.




So for example I could encounter this kind of matrix:

m2 <- matrix(c('a','b','d',NA,NA,'c',NA, 'c', NA), 3,3, byrow=TRUE)


       [,1] [,2] [,3]
[1,] "a"  "b"  "d" 
[2,] NA NA  "c" 
[3,] NA "c"  NA  

which should also be transformed into:

        [,1] [,2] [,3] [,4]
[1,]  "a"  "b"  "c"  "d" 
[2,] NA NA NA NA


(or m3 <- matrix(c('a','b','d',NA,'c',NA,NA, NA, 'c'), 3,3, byrow=TRUE) ).



Can perhaps someone give me some hints how to solve this efficiently?

I think I could solve that with some loops … but I also need to make sure that it is efficient / not taking too much time.


thanks!



More information about the R-help mailing list