Question :
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 want you to be able to generate another vector that grows and decreases monotonically, whatever increment I choose. The output for this vector with the increment of 1 would be:
> b
[1] 1 2 3 2 1 -1 -2 -3 -4 -5
Ideally, you should not use a loop.
Answer :
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 equal consecutive values, 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))))