Replace values to either always increase or be the same as value before it

Viewed 40

My specific desire is hard to describe without an example, so here it goes. The raw data I have looks like this:

Data <- data.table(ID = c("Car1", "Car2", "Car3", "Car4", "Car5", "Car6"),
                   Consumer_Teir = c(1,2,1,2,3,3))

I want to replace the Consumer_Teir values so they are always increasing or the same as the value before it. So in this example, the 1 that is surrounded by 2s should become a 2.

Desired output:

Data <- data.table(ID = c("Car1", "Car2", "Car3", "Car4", "Car5", "Car6"),
                   Consumer_Teir = c(1,2,2,2,3,3))

My actual data may have a 2 with a large back of 1s after it, so a straight x1>x2 | x1==x2 may not actually work without a repeating loop, which is very time intensive. I'm sure there is a type of fill that does this, but I don't know what this fill is to be able to find it.

Thanks!

1 Answers

We could use cummax

Data[, Consumer_Teir := cummax(Consumer_Teir)]
Related