I have a vector v
and I would like to find the index of first changes in elements of a vector in R. How can I do this? For example:
v = c(1, 1, 1, 1, 1, 1, 1, 1.5, 1.5, 2, 2, 2, 2, 2)
Element access:at(g) – Returns a reference to the element at position 'g' in the vector. front() – Returns a reference to the first element in the vector. back() – Returns a reference to the last element in the vector.
To get the first element of a vector, we could do the following. In R, array indexes start at 1 - the 1st element is at index 1. This is different than 0-based languages like C, Python, or Java where the first element is at index 0.
Use the which() Function to Find the Index of an Element in R. The which() function returns a vector with the index (or indexes) of the element which matches the logical vector (in this case == ).
Vector Indexing, or vector index notation, specifies elements within a vector. Indexing is useful when a MATLAB program only needs one element of a series of values. Indexing is often used in combination with repetition structures to conduct the same process for every element in an array.
You're looking for rle
:
rle(v)
## Run Length Encoding
## lengths: int [1:3] 7 2 5
## values : num [1:3] 1 1.5 2
This says that the value changes at locations 7+1, 7+2+1 (and 7+2+5+1 would be the index of the element "one off the end")
rle
is a good idea, but if you only want the indices of the changepoints you can just do:
c(1,1+which(diff(v)!=0))
## 1 8 10
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