在基礎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))
來源
2016-10-19 14:06:07
lmo
封裝['markovchain'](https://cran.rstudio.com/web/packages/markovchain/index.html)。 – tchakravarty
'prop.table(table(old,new),margin = 2)'應該在base R中非常接近。 – lmo
@lmo - 看起來像是一個完全可以接受的答案,並且完全符合他們的要求。國際海事組織你應該張貼。 – Dason