Trung Luu
Trung Luu

Reputation: 45

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.

Upvotes: 3

Views: 196

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 102519

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

Upvotes: 2

Benjamin Christoffersen
Benjamin Christoffersen

Reputation: 4841

This might do:

p1 <- head(point, -1)
p2 <- point[-1]
keep <- p1 != p2
table(paste0("Transit_", p1[keep], "_", p2[keep]))
#R> 
#R> Transit_A_B Transit_A_C Transit_B_A Transit_B_C Transit_C_A Transit_C_B 
#R>           2           2           2           1           1           1 

and if you wanted the printed output like you show:

p1 <- head(point, -1)
p2 <- point[-1]
keep <- p1 != p2
out <- table(paste0("Transit_", p1[keep], "_", p2[keep]))

cat(paste0(names(out), ": ", out, 
           ifelse(seq_along(out) == length(out), ".", ";")),
    sep = "\n")
#R> Transit_A_B: 2;
#R> Transit_A_C: 2;
#R> Transit_B_A: 2;
#R> Transit_B_C: 1;
#R> Transit_C_A: 1;
#R> Transit_C_B: 1.

Upvotes: 2

Related Questions