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.
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),])