A <- matrix(c( 1,1,1,1,0,1,1,1,1, 1,1,1,0,1,0,1,0,0, 1,0,1,0,0,1,0,0,0, 1,1,0,0,0,0,1,0,0), 4, 9, byrow=TRUE) apply(A, 1, function(x) sum(diff(x)==1))