Brani - 9 months ago 67

R Question

The following vector contains month numbers.

`x <- c(10,4,10,12,1,3,6,7,9,11,12,4,7,8)`

Specifically, the first element is the 10th month of some year, the second is the 4th month of the next year, etc.

I am looking for a way to add 12 in the elements of x, where needed, so that I get a vector y like this:

`y <- c(10,16,22,24,25,27,30,31,33,35,36,40,43,44)`

How would you suggest to do it?

Answer

We can compare the adjacent elements with `diff`

, check whether it is less than 0 to create a logical vector, concatenate with `FALSE`

to account for the length difference in output of `diff`

, get the `cumsum`

, multiply by 12 and add to x

```
x+ cumsum(c(FALSE, diff(x)< 0)) *12
#[1] 10 16 22 24 25 27 30 31 33 35 36 40 43 44
```