Home > other >  How can I replace vector values with ascending numbers using the same intervals
How can I replace vector values with ascending numbers using the same intervals

Time:06-17

I am trying to replace values of a vector with different intervals, such that the intervals are numbered from 1 to last interval. For example,

x <- c(5, 5, 5, 7, 7, 7, 9, 11, 11, 11, 15, 15, 15, 17, 17, 17, 17)

I want to be like this:

y <- c(1, 1, 1, 2, 2, 2, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6)

Is there a way to this automatically?

Thanks for any help.

Follow-up question:

What if you want to keep the gabs in your new vector? For example, if we have:

x <- c(5, 5, 7, 7, 8, 8, 9)

I want it to be:

y <- c(1, 1, 3, 3, 4, 4, 5)

CodePudding user response:

You can do

match(x, unique(x))
#> [1] 1 1 1 2 2 2 3 4 4 4 5 5 5 6 6 6 6

Or

as.numeric(factor(x))
#> [1] 1 1 1 2 2 2 3 4 4 4 5 5 5 6 6 6 6

Or

1   c(0, cumsum(sign(diff(x))))
#> [1] 1 1 1 2 2 2 3 4 4 4 5 5 5 6 6 6 6

CodePudding user response:

rleid from data.table:

x <- c(5, 5, 5, 7, 7, 7, 9, 11, 11, 11, 15, 15, 15, 17, 17, 17, 17)
data.table::rleid(x)
#>  [1] 1 1 1 2 2 2 3 4 4 4 5 5 5 6 6 6 6

Follow-up - to keep the gaps:

x - x[1]   1
#>  [1]  1  1  1  3  3  3  5  7  7  7 11 11 11 13 13 13 13
  •  Tags:  
  • r
  • Related