如何在R中创建转换矩阵

时间:2013-09-16 05:03:22

标签: r

我一直试图计算1950年1月份的一个月后续事件的数量,以形成马尔可夫链的转移概率矩阵:

E00 = dry day after dry day
E01 = wet day after dry day
E10 = dry day after wet day
E11 = wet day after wet day

干燥日意味着降雨量= 0,湿日意味着降雨量> 0。

如何使用R计算上述内容?我尽力用逻辑语句编写函数但不能。有人可以帮帮我吗?

数据:

day,month,year,rainfall
1,01,1950,0.586212158
2,01,1950,1.202758789
3,01,1950,0
4,01,1950,0
5,01,1950,0
6,01,1950,0.183441162
7,01,1950,4.675704956
8,01,1950,9.258003235
9,01,1950,3.425468445
10,01,1950,0
11,01,1950,0
12,01,1950,8.39233E-05
13,01,1950,0
14,01,1950,0
15,01,1950,0.641731262
16,01,1950,9.325141907
17,01,1950,5.588417053
18,01,1950,0.903343201
19,01,1950,3.892127991
20,01,1950,0.133895874
21,01,1950,0.102630615
22,01,1950,5.334564209
23,01,1950,1.017593384
24,01,1950,0
25,01,1950,0.621734619
26,01,1950,0.957794189
27,01,1950,3.131622314
28,01,1950,4.868865967
29,01,1950,0.169281006
30,01,1950,0
31,01,1950,0

1 个答案:

答案 0 :(得分:3)

我认为你做的事情的一种方式(它可能更简洁):

# assuming the data is read into a data frame called "raindata"
rf <- raindata$rainfall
n <- length(rf)
rainedf <- as.factor(ifelse(rf,0,1))
trf <- table(data.frame(yesterday=rainedf[1:(n-1)],today=rainedf[2:n]))
trf/rowSums(trf)