Samir
Samir

Reputation: 3

Detecting irregularities in binary sequence

In my dataset, each person has 11 answers to questions. The answers are stored with 0s (wrong) and 1s (right). So, I need to detect switching points from 0s to 1s. So, possible cases:

example

id 1 2 3 4 are regular responses because they either have one switching point or none.

id 5 and 6 are irregular responses because they have two switching points.

So, I need to have a column (consistent) and mark regular (one switching point or none) and irregular (multiple switching points) rows.

Any help would be highly appreciated!

Upvotes: 0

Views: 59

Answers (1)

chinsoon12
chinsoon12

Reputation: 25225

Assuming that you dataset is a data.frame, you can use the abs of the diff of each row to identify switched. Then sum the number of switches to get the Consistent column

DF$Consistent <- apply(DF, 1, function(x) as.numeric(sum(abs(diff(x))) <= 1))

data:

DF <- as.data.frame(rbind(c(0,0,0,1,1), c(1,1,0,0,0), c(1,1,1,1,1), c(0,0,0,0,0), c(1,0,1,0,0), c(0,0,0,1,0)))

Upvotes: 1

Related Questions