Search code examples
rtransitionpoint

How to count the number of transition between different points in R


I am a beginner in R.

I have a vector of points like:

point <- c("A","B","B","C","C","A","A","C","B","A","B","A","A","C")

And I would like to count the number of transition between different points. That mean I would like the output as:

Transit_A_B: 2;
Transit_A_C: 2;
Transit_B_C: 1;
Transit_B_A: 2;
Transit_C_B: 1;
Transit_C_A: 1.

Many thanks to anyone can help me.


Solution

  • Maybe you can try embed like below

    df <- rev(data.frame(embed(point, 2)))
    res <- table(
      paste0(
        "Transit_",
        do.call(paste, c(subset(df, do.call("!=", df)), sep = "_"))
      )
    )
    

    which gives

    > res
    
    Transit_A_B Transit_A_C Transit_B_A Transit_B_C Transit_C_A Transit_C_B
              2           2           2           1           1           1
    

    If you prefer the result in the format of data frame, you can apply stack over res, e.g.,

    > stack(res)
      values         ind
    1      2 Transit_A_B
    2      2 Transit_A_C
    3      2 Transit_B_A
    4      1 Transit_B_C
    5      1 Transit_C_A
    6      1 Transit_C_B