r - How to check if a vector contains n consecutive numbers -
suppose vector numbers contains c(1,2,3,5,7,8), , wish find if contains 3 consecutive numbers, in case, 1,2,3.
numbers = c(1,2,3,5,7,8) difference = diff(numbers) //the difference output 1,1,2,2,1
to verify there 3 consecutive integers in numbers vector, i've tried following little reward.
rep(1,2)%in%difference
the above code works in case, if difference vector = (1,2,2,2,1), still return true though "1"s not consecutive.
using diff
, rle
, should work:
result <- rle(diff(numbers)) any(result$lengths>=2 & result$values==1) # [1] true
in response comments below, previous answer testing runs of length==3
excluding longer lengths. changing ==
>=
fixes this. works runs involving negative numbers:
> numbers4 <- c(-2, -1, 0, 5, 7, 8) > result <- rle(diff(numbers4)) > any(result$lengths>=2 & result$values==1) [1] true
Comments
Post a Comment