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?