[R] counting strings of identical values in a matrix
Marc Schwartz
marc_schwartz at comcast.net
Thu Nov 15 18:25:43 CET 2007
On Thu, 2007-11-15 at 17:53 +0100, A M Lavezzi wrote:
> thank you.
> I did not think about the case of overlapping of
> 1's from the end of one column to the start of the next,
> this would actually be a problem
>
> In the simulations I am running each column
> corresponds to the path followed by an agent
> across states of a stochastic process,
> so I would like to avoid mixing up two different
> paths (I made a mistake when I mentioned the possibility of turning my matrix
> into a vector, sorry about that).
>
> can I kindly ask again your help on this?
>
> please excuse me.
>
> Mario
<snip>
Not a problem. After sending my follow up, I suspected that you might
need a more general approach. This sort of ends up being a combination
of the first two, in order to keep each column sequence intact:
res <- do.call(cbind, apply(prova, 2,
function(x) do.call(rbind, rle(x))))
> res
[3,] [5,] [7,] [4,] [7,] [4,] [8,] [2,] [3,]
lengths 2 2 2 2 3 3 2 3 4 1 1 1 6
values 3 1 3 1 3 1 3 3 1 3 3 1 3
> table(res["lengths", res["values", ] == 1])
1 2 3 4
1 2 1 1
I think that should do it, but you might want to test it on a known set
of data.
HTH,
Marc
More information about the R-help
mailing list