We can create a grouping variable, taking the difference of adjacent elements, check if it is equal to 1, get cumsum , use tapply to get the result of length and sum .
sum(tapply(int.vec,cumsum(c(TRUE,diff(int.vec) !=1)), FUN=length)) #[1] 10
Or use table and sum
sum(table(int.vec,cumsum(c(TRUE,diff(int.vec) !=1)))) #[1] 10
Or we split "int.vec" with the grouping variable obtained from cumsum ( split , very fast) and get the length each list element using lengths (another quick option) - contributed by @Frank
sum(lengths(split(int.vec, cumsum(c(0,diff(int.vec)>1)))))
NOTE. No packages are used. This will be useful for identifying the individual length each component (if necessary), simply by removing the sum wrapper.
Based on additional information from @Symbolix's solution, the expected OP output is only length for vector .
NROW(int.vec) #[1] 10
. This will also work if we work with data.frame . But, as I mentioned above, it seems that the OP needs to identify both the length each interval and the length . This solution provides both.
source share