# COUNTIF: "value" followed by "value"

I would appreciate advice on how to perform the following COUNTIF function:

For a vector only containing ones and zeros, that is a dummy variable, I need to count the number of ones (TRUE) followed by a one (TRUE), the number of zeros (FALSE) followed by a zero (FALSE), etc.

In some kind of noob terms this would be:

``````sum(MyVector[i+1] == MyVector[i])

OR

sum(if(MyVector[i] == 1 & MyVector[i + 1] == 1))
``````

Would this work for you?

``````x <- sample(c(0, 1), size = 100, replace = TRUE)
sum(x[1:(length(x)-1)] == x[2:length(x)])
``````

Many thanks Leon, but Im afraid it is too general. Your function does the counting for all the values in the vector, both zeros and ones, at the same time. How can I do the same thing when the function only looks at ones, or only looks at zeros? I tried the following, but obviously it did not work.

``````ifelse(x == 1, sum(x[1:(length(x)-1)] == x[2:length(x)]), NA)

Could we tell the sum function in some way:

for x[i] == 1
sum(x[1:(length(x)-1)] == x[2:length(x),])

``````

Edit:

This seems to work but I get a warning message:

``````sum(x[1:(length(x)-1)] == x[2:length(x)] & x[] == 0)
``````

Which yields the correct sum for zeros followed by a zero, but also the following warning:

Warning message:
longer object length is not a multiple of shorter object length

``````count_neighbours <- function(x, y){
return(sum(which(x == y)[-1] == (which(x == y)+1)[-sum(x == y)]))
}
x <- sample(c(0, 1), size = 10, replace = TRUE)
count_neighbours(x, 0)
count_neighbours(x, 1)
``````

?

Thanks for another solution! Much appreciated. I have chosen to implement your first solution though as it was more straightforward. By setting ...

``````sum(I.95[1:(length(I.95)-1)] == I.95[2:length(I.95)] & I.95[][-1] == 1)
``````

...I got rid of the warning message.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.