Let's say I have this integer vector:
> int.vec
[1] 1 2 3 5 6 7 10 11 12 13
(created from int.vec <- c(1:3,5:7,10:13))
I'm looking for a function that will return the sum of the lengths of all intervals in this vector.
So basically for int.vec this function will return:
3+3+4 = 10
length(int.vec)
# 10
Your intervals are sequences of numbers, x1:xn, x1:xm, x1:xp, where the length of each vector (or interval in this case) is n, m, and p respectively.
The length of the whole vector is length(x1:xn) + length(x1:xm) + length(x1:xp),
which is the same as length(n + m + p).
Now, if we really are interested in the length of each individual vector of sequences, we can do
int.vec <- c(1:3,5:7,10:13)
## use run-length-encoding (rle) to find sequences where the difference == 1
v <- rle(diff(int.vec) == 1)[[1]]
v[v!=1] + 1
# [1] 3 3 4
And, as pointed out by @AHandcartAndMohair, if you're working with a list you can use lengths
int.list <- list(c(1:3), c(5:7), c(10:13))
lengths(int.list)
# [1] 3 3 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With