[R] "Improvement with the R code"

niharika singhal niharikasinghal1990 at gmail.com
Mon Aug 28 16:37:42 CEST 2017


Hello,

I am trying to implement a formula

 aij= transition from state S_i to S_j/no of transition at state S_i



Code I have written is working with three state {1,2,3 }, but if the number
of states become={1,2,3,4,......n} then the code will not work, so can some
help me with this.

For   and some rows of my  data frame look like

checkdf=data.frame(clusterNum=c(3,2,3,1,1,3,4,3,2,1,1,3,2,1,3,2)
no_of_state=3
transition_matrix=matrix(NA,nrow=no_of_state, ncol=no_of_state)
for(k in 1: no_of_state)
{
  count1=0
  count2=0
  count3=0
  #For last point no transition takes place
  for(j in 1: (nrow(checkdf)-1))
  {

    if(checkdf$clusterNum[j]==k)
    {
      if(checkdf$clusterNum[j+1]==1){
        count1=count1+1
      }
      else if(checkdf$clusterNum[j+1]==2){
        count2=count2+1
       }
      else {
        count3=count3+1
       }
    }
  }

  no_of_points=(count1+count2+count3)
  s1=count1/no_of_points
  s2=count2/no_of_points
  s3=count3/no_of_points
  transition_matrix[k,]=c(s1, s2, s3)

}

I know the code is not written nicely and I want to improve it.

Thanks in advance
Niharika

	[[alternative HTML version deleted]]



More information about the R-help mailing list