create sequence that increases and decreases monotonically

Asked

Viewed 41 times

3

I have the following vector:

> a
 [1]  64.42  66.99 100.39  97.96  97.96  96.26  94.22  92.35  86.05  84.01

I wish that I could generate another vector that grows and decreases monotonically, whatever the increment I choose. The output for this vector with increment 1 would be:

> b
 [1]  1  2  3  2  1 -1 -2 -3 -4 -5 

The ideal would be not to use a loop.

  • 1

    The 4th and 5th values are equal, so it shouldn’t be the output 1 2 3 2 2 1 0 -1 -2 -3? (Two values equal to 2, in the same positions.)

  • exact, I’ll edit

1 answer

3


First the data.

a <- scan(text = "64.42  66.99 100.39  97.96  97.96
                  96.26  94.22  92.35  86.05  84.01")

Now, if my comment above is correct, we can solve the problem with a single line of code R.

d <- cumsum(c(1, sign(diff(a))))
d
[1]  1  2  3  2  2  1  0 -1 -2 -3

For example, with a sequence that does not have two consecutive values equal, the same command gives the desired result.

set.seed(4863)
b <- runif(10, 60, 110)
b <- c(sort(b[1:3]), sort(b[4:10], decreasing = TRUE))
b

cumsum(c(1, sign(diff(b))))
[1]  1  2  3  4  3  2  1  0 -1 -2

This can be written as a function of a line.

sobe_desce <- function(x) cumsum(c(1, sign(diff(x))))
  • Thanks Rui, very simple code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.