skinnyas123
skinnyas123

Reputation: 382

Create sequence based on a condition

How to conditionally increment if the previous value is greater than the current value? Say I have a column x on my data frame and I want a column y which starts from 1 and increments if the previous value is greater than the current.

x   y
1   1
2   1
3   1
4   1
5   1
6   1
1   2
2   2
3   2
4   2
5   2
6   2
7   2
8   2
1   3
2   3
5   3

Upvotes: 2

Views: 249

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388817

As @A5C1D2H2I1M1N2O1R2T1 mentioned, you can use cumsum with diff to generate y.

cumsum(diff(x) < 0) + 1
#[1] 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3

You might want to prepend 1 in the beginning to get y with same length as x.

c(1, cumsum(diff(x) < 0) + 1)
#[1] 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3

data

x <- c(1:6, 1:8, 1, 2, 5)

Upvotes: 1

Related Questions