[R] Convert timeseries to transition matrix

Gabor Grothendieck ggrothendieck at myway.com
Tue Mar 22 17:35:33 CET 2005


Ingmar Visser <i.visser <at> uva.nl> writes:

: 
: Hi All,
: Does someone have an idea of how to cleverly convert a categorical
: timeseries into a transition matrix?
: Ie, I have something like:
: x<- c(1,1,2,1,1,2,2,2,1,2),
: And I want a matrix with counts and/or probabilities:
: > tr <- matrix(c(2,3,2,2),2,2)
: > tr
:      [,1] [,2]
: [1,]    2    2
: [2,]    3    2
: Meaning that there are two transitions from 1 to 1, two from 1 to 2, three
: from 2 to 1 and two from 2 to 2.
: Using for loops etc this is of course no problem, but I am curious whether
: there is a smarter solution.
: Any hints appreciated, Ingmar
: 


Try this:

table(from = x[-length(x)], to = x[-1])

It gives the transpose of tr in your example since there are actually
three transitions from 1 to 2, not three transitions from 2 to 1.




More information about the R-help mailing list