2016-10-19 90 views
2

讓我們假定我們有以下4種狀態:(A,B,C,d)計算在R上的轉移概率

表我有以下格式

old new 
A  B 
A  A 
B  C 
D  B 
C  D 
.  . 
.  . 
.  . 
.  . 

我想該計算基於在表中給出的數據如下概率:

P(new=A | old=A) 
P(new=B | old=A) 
P(new=C | old=A) 
P(new=D | old=A) 
P(new=A | old=B) 
. 
. 
. 
. 
P(new=C | old=D) 
P(new=D | old=D) 

我能做到以手動方式,總結所有的值時每個過渡發生和通過的行數除以,BU t我想知道R中是否有內置函數來計算這些概率,或者至少有助於係數計算這些概率。

任何幫助/輸入將不勝感激。如果沒有這樣的功能,那好吧。

+0

封裝['markovchain'](https://cran.rstudio.com/web/packages/markovchain/index.html)。 – tchakravarty

+3

'prop.table(table(old,new),margin = 2)'應該在base R中非常接近。 – lmo

+0

@lmo - 看起來像是一個完全可以接受的答案,並且完全符合他們的要求。國際海事組織你應該張貼。 – Dason

回答

8

在基礎R,你可以一個表對象上使用prop.table

transMat <- prop.table(with(df, table(old, new)), 2) 
transMat 
    new 
old   A   B   C   D 
    A 0.26315789 0.27272727 0.18181818 0.22222222 
    B 0.31578947 0.36363636 0.09090909 0.22222222 
    C 0.21052632 0.27272727 0.45454545 0.33333333 
    D 0.21052632 0.09090909 0.27272727 0.22222222 

這裏,列之和爲1:

colSums(transMat) 
A B C D 
1 1 1 1 

編輯 在進一步的思考,我認爲使用因爲p(A | A)+ p(B | A)+ p(C | A)+ p(D | A)應該相等,所以margin = 1實際上就是期望的結果,因爲old(條件變量) 1.在這種情況下,

transMat <- prop.table(with(df, table(old, new)), 1) 
transMat 
    new 
old   A   B   C   D 
    A 0.41666667 0.25000000 0.16666667 0.16666667 
    B 0.46153846 0.30769231 0.07692308 0.15384615 
    C 0.26666667 0.20000000 0.33333333 0.20000000 
    D 0.40000000 0.10000000 0.30000000 0.20000000 

將工作。或者,轉碼prop.table(with(df, table(new, old)), 2)

數據

set.seed(1234) 
df <- data.frame(old=sample(LETTERS[1:4], 50, replace=TRUE), 
       new=sample(LETTERS[1:4], 50, replace=TRUE))