1

If my df consist of

M
M
D
M
D
S
M
K
M

So the idea is a for loop to go through each row and count the combination for a transition matrix with the final output as

  M D S K
M 1 2 0 1
D 1 0 1 0
S 1 0 0 0
K 1 0 0 0

I've found from previous post suggesting the use of

result <- expand.grid(unique(my.vec), unique(my.vec)) %>% mutate(count = 0)
for (i in 1:(length(my.vec)-1)){
  currentVal = my.vec[i]
  nextVal = my.vec[i+1]
  result[result$Var1 == currentVal & result$Var2==nextVal,]$count = result[result$Var1 == currentVal & result$Var2==nextVal,]$count +1
}

but expand.grid will need to be defined.

Is there a way to use a straight for loop?

Werrby
  • 41
  • 6

1 Answers1

1
v <- ordered(df$V1, unique(df$V1))
table(head(v,-1), tail(v,-1))
  
    M D S K
  M 1 2 0 1
  D 1 0 1 0
  S 1 0 0 0
  K 1 0 0 0

df <- structure(list(V1 = c("M", "M", "D", "M", "D", "S", "M", "K", 
"M")), class = "data.frame", row.names = c(NA, -9L))
Onyambu
  • 67,392
  • 3
  • 24
  • 53
  • Hi Onyambu, Thanks for your suggestion. I can see that the list will need to be specified for the final matrix. There are 26000 rows in my actual data set with these 4 states (M,D,S,K) so I'm wondering if there is another way to construct the final matrix. – Werrby Nov 02 '22 at 04:09
  • Nothing will have to be manually constructed here, except for specifying the `M/D/S/K` order you wish to have the rows and columns shown in when making the `ordered()` factor. It's a brilliantly simple answer. – thelatemail Nov 02 '22 at 04:19
  • @Werrby read the comment by thelatemail above. – Onyambu Nov 02 '22 at 04:32
  • @Werrby Which list are you talking about? Why do you need another way of creating the final matrix? – Onyambu Nov 02 '22 at 04:33
  • Hi @onyambu, I'm very new to R and is wondering if you can explain a few elements please. how would V1 translates to a csv file? what does -9L mean in row names? Thanks – Werrby Nov 02 '22 at 05:09
  • @Werrby V1 is not a csv file but rather the column name. you presented your data as a dataframe and not as a vector. if you want the code to directly translate to your work, use `v <- ordered(my.vev, c("M", "D", "S", "K"))` then do the `table` command above. There is no csv file involved here – Onyambu Nov 02 '22 at 05:16