Klausos Klausos
Klausos Klausos

Reputation: 16060

Vector: How to filter out segments of decreasing values

Let's say there is a vector sim that contains the following sequence of numbers:

1
2
4
7
5
3
2.5
4
6

How can I filter out all the segments of decreasing values in order to achieve sim with only increasing values? The expected result:

1
2
4
7
2.5
4
6

Upvotes: 2

Views: 158

Answers (1)

J.R.
J.R.

Reputation: 3888

Based on @akrun's suggestion:

dif <- diff(sim) > 0
sim[ c(dif[1], dif) | c(dif, dif[length(dif)]) ]
[1] 1.0 2.0 4.0 7.0 2.5 4.0 6.0

Upvotes: 4

Related Questions