Is there a way to count sequence of 0 and 1 in R?

Viewed 50

I have the following data as an excel file:

X
0
0
1
1
0
0

I want to count the number of times I have the following sequence:

00
11
10
01

I desire the following output:

Sequence Count

00 2
11 1
01 1
10 1

I tried using count but I could not come up with anything useful. count.seq serves a similar purpose but it estimates for DNA or RNA sequence data.

1 Answers
x <- c(0, 0, 1, 1, 0, 0)
n <- length(x)
s <- paste0(x[-n], x[-1L])
s
## [1] "00" "01" "11" "10" "00"

table(factor(s, levels = c("00", "01", "10", "11")))
## 00 01 10 11 
##  2  1  1  1
Related