1

I have been struggling with this problem for quite a while and any help would be much appreciated.

I am trying to write a function to calculate a transition matrix from observed data for a markov model.

My initial data I am using to build the function look something like this;

 Season                 Team State
1        1    Manchester United     1
2        1              Chelsea     1
3        1      Manchester City     1
.
.
.
99       5    Charlton Athletic     4
100      5              Watford     4

with 5 seasons and 4 states.

I know how I am going to calculate the transition matrix, but in order to do this I need to count the number of teams that move from state i to state j for each season.

I need code that will do something like this,

a<-function(x,i,j){
if("team x is in state i in season 1 and state j in season 2") 1 else 0
}
sum(a)

and then I could do this for each team and pair of states and repeat for all 5 seasons. However, I am having a hard time getting my head around how to tell R the thing in quotation marks. Sorry if there is a really obvious answer but I am a rubbish programmer.

Thanks so much for reading!

Cdog
  • 11
  • 1

1 Answers1

1

This function tells you if a team made the transition from state1 to state2 from season1 to season2

a <- function(team, state1, state2, data, season1, season2) {  
  team.rows = data[team == data["Team",],]   
  in.season1.in.state1 = ifelse(team.rows["Season",]==season1 && team.rows["State",state1],1,0)
  in.season2.in.state2 = ifelse(team.rows["Season",]==season2 && team.rows["State",state2],1,0)   
  return(sum(in.season1.in.stat1) * sum(in.season2.in.state2)) 
}
  • In the first line I select all rows of a particular team.
  • The second line is determining for each entry if a team is ever in state1 in season1.
  • The third line is determining for each entry if a team is ever in state2 in season2,
  • and the return statement returns 0 if the team was never in the respective state in the respective season or 1 otherwise (only works if there are no duplicates, in that case it might return a value greater than 1)
schadr
  • 398
  • 2
  • 10
  • Thank you so much! This is a great starting point for me to expand to other seasons! – Cdog Jun 26 '12 at 10:07