Home > other >  find positions where vector decreases
find positions where vector decreases

Time:03-09

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

CodePudding user response:

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
  • Related