PyLabour
PyLabour

Reputation: 265

How to create a transition matrix in R

I have been trying to calculate the number of following events in a month say January, 1950 to form transition probability matrix of Markov chain:

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

Dry day means rainfall = 0 and wet day means rainfall>0.

How can I calculate these above using R? I have tried my best to write a function with logical statements but cannot. Could anyone please help me?

data:

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

Upvotes: 0

Views: 15064

Answers (1)

Glen_b
Glen_b

Reputation: 8262

One way to do what I assume you're after (it's possible to be briefer):

# 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)

Upvotes: 3

Related Questions