Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the index of first changes in the elements of a vector

Tags:

r

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)
like image 668
rose Avatar asked Jan 03 '14 03:01

rose


People also ask

How do you find the index element of a vector?

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.

What is the index to the first element to a vector in R?

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.

How do you get the index of an element in a vector in R?

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 == ).

What does it mean to index a vector?

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.


2 Answers

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")

like image 55
Matthew Lundberg Avatar answered Oct 16 '22 15:10

Matthew Lundberg


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
like image 38
Ben Bolker Avatar answered Oct 16 '22 14:10

Ben Bolker