user3742038
user3742038

Reputation: 77

Sequentially rank vector

I have a vector of random numbers:

a <- rnorm(10)

I would like to do the following:

  1. start form the first element and compare it to the second 2.if the second element is larger than the first proceed to the third element otherwise print the position of the sequentially highest element (2)
  2. if the third element is larger than the fourth, proceed to the fourth element, otherwise print the position of the sequentially highest element (3)

and so on until the sequence ends.

So for example:

if the numbers are 1 4 5 3 1

I start by comparing 1 and 4 and since 4 is larger I proceed then I compare 4 and 5 and since 5 is larger I proceed then I compare 5 and 3 and since 3 is small I stop and print the position of 5 which is the position of the highest element in the sequence.

Upvotes: 1

Views: 71

Answers (3)

Pierre L
Pierre L

Reputation: 28441

Example:

set.seed(1118)
s <- sample(10)
s
[1]  5  4 10  8  9  3  6  7  1  2

With the example above we can look use diff to isolate positive changes in the sequence:

which(diff(s) < 0)
[1] 1 3 5 8

edit:

For the first value only subset the vector of higher numbers in the sequence:

which(diff(s) < 0)[1]
[1] 1

Your original example:

s <- c(1, 4, 5, 3, 1)
which(diff(s) < 0)[1]
[1] 3

Upvotes: 2

LyzandeR
LyzandeR

Reputation: 37879

Maybe using Position:

a <- c(1,4,5,3,1)

#position will find the first element in the diff(a) that is negative
#and will output its position. The vector diff is n-1 the length
#of a so this will result in printing the position required by the OP
Position(function(x) x < 0 , diff(a))
[1] 3

Upvotes: 3

Benjamin
Benjamin

Reputation: 17369

min(which(diff(x) < 0)) should do the trick

x <- c(1, 4, 5, 3, 1)
min(which(diff(x) < 0))
x[min(which(diff(x) < 0))]


set.seed(1)
a<-rnorm(10)
min(which(diff(a) < 0)) 

Upvotes: 1

Related Questions