ujjwal tyagi
ujjwal tyagi

Reputation: 493

find positions where vector decreases

x<-c(2 ,1, 3 ,1, 3, 4)

The vector here decreases at two places. This is just an example vector. Here at second position and at 4rth position the vector decreases(from 2 to 1 and from 3 to 1) . I want to find these positions

Upvotes: 0

Views: 35

Answers (1)

Thomas Guillerme
Thomas Guillerme

Reputation: 1857

You can check that by simply comparing the vector to itself with a shift:

x < c(0,x[-length(x)])
[1] FALSE  TRUE FALSE  TRUE FALSE FALSE

where you shift x by one value (introducing the 0 and ignoring the last value of x, length(x)).

To find which positions are decreasing you can use which on that logical vector:

which(x < c(0,x[-length(x)]))
[1] 2 4

Upvotes: 2

Related Questions