Question

I have a transition matrix m:

m <- matrix(c(0, 0, 1, 0, 0, 0, 0,
               0, 1, 1, 0, 0, 0, 0,
               1, 0, 1, 1, 0, 0, 0,
               0, 0, 0, 1, 1, 0, 0,
               0, 0, 0, 0, 0, 0, 1,
               0, 0, 0, 0, 0, 1, 1,
               0, 0, 0, 1, 1, 0, 1), 
             nrow = 7, ncol = 7, byrow = TRUE,
             dimnames = list(c("d1", "d2", "d3", "d4", "d5", "d6", "d7"),
                             c("d1", "d2", "d3", "d4", "d5", "d6", "d7"))
             );

and would like a transition probability matrix that looks like this (adding up to 1.0 for each row).

0.00   0.00   1.00   0.00  0.00   0.00   0.00
0.00   0.50   0.50   0.00  0.00   0.00   0.00
0.33   0.00   0.33   0.33  0.00   0.00   0.00
...

Is there a standard function that allows me to do that?

Était-ce utile?

La solution

You can use prop.table:

prop.table(m, 1)

          d1  d2        d3        d4        d5  d6        d7
d1 0.0000000 0.0 1.0000000 0.0000000 0.0000000 0.0 0.0000000
d2 0.0000000 0.5 0.5000000 0.0000000 0.0000000 0.0 0.0000000
d3 0.3333333 0.0 0.3333333 0.3333333 0.0000000 0.0 0.0000000
d4 0.0000000 0.0 0.0000000 0.5000000 0.5000000 0.0 0.0000000
d5 0.0000000 0.0 0.0000000 0.0000000 0.0000000 0.0 1.0000000
d6 0.0000000 0.0 0.0000000 0.0000000 0.0000000 0.5 0.5000000
d7 0.0000000 0.0 0.0000000 0.3333333 0.3333333 0.0 0.3333333

Here, the argument 1 means that the function is applied to each row separately.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top