[R] algorithm to merge same entries in a matrix
Paul Hiemstra
paul.hiemstra at knmi.nl
Wed Aug 31 11:29:49 CEST 2011
Hi,
Take a look at the rle() function. This finds runs of equal values in
vectors. Using apply this can quite easily be run for all the
rows/columns of a matrix.
cheers,
Paul
On 08/30/2011 04:58 PM, Martin Batholdy wrote:
> 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!
>
> ______________________________________________
> 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.
--
Paul Hiemstra, Ph.D.
Global Climate Division
Royal Netherlands Meteorological Institute (KNMI)
Wilhelminalaan 10 | 3732 GK | De Bilt | Kamer B 3.39
P.O. Box 201 | 3730 AE | De Bilt
tel: +31 30 2206 494
http://intamap.geo.uu.nl/~paul
http://nl.linkedin.com/pub/paul-hiemstra/20/30b/770
More information about the R-help
mailing list