# I am trying to fill a new column with 1-2 sequence any time the number increases from one digit to another .

``````##this is what I did
x1=c(4463, 4463,  4463,  4463, 4335,4335,4335, 4335,4330,4330,4330)

x=as.data.frame(x1)
x\$data <- 1+((x\$x1-1) %%2)
x
## but with the x\$data <- 1+((x\$x1-1) %%2), it did not change to 2 when it reaches 4335// I wonder why?
##this is the result I would like
x3=c(4463,4463,4463,4463,4335,4335,4335,4335,4330,4330,4330)

x5=as.data.frame(x3)
x5\$data=c(1,1,1,1,2,2,2,2,1,1,1)
x5
``````

The reason the value did not change is that in terms of modular arithmetic, when the modulus is 2, odd numbers are 1 and even numbers are 0. Therefore, the formula provided subtracts 1 from each value, carries out the modular arithmetic, and then adds 1. So, all odd numbers will get the same result, and all even numbers will get the same (different) result.

Below is one example of how to tell when a number changes to another number in a vector using the `lag()` function from dplyr.

``````x1=c(4463, 4463,  4463,  4463, 4335,4335,4335, 4335,4330,4330,4330)

library(tidyverse)

x = data.frame(X1 = x1) %>%
mutate(data = case_when(
row_number() == 1 ~ 0,
X1 == lag(X1) ~ 0,
TRUE ~ 1
)) %>%
mutate(data = cumsum(data)) %>%
fill(data) %>%
mutate(data = data %% 2 + 1)

x\$data
#>   1 1 1 1 2 2 2 2 1 1 1
``````

Created on 2023-02-05 with reprex v2.0.2.9000

1 Like

does what it was asked, but `x1` and `x3` don't differ.

``````x1 <- c(4463, 4463, 4463, 4463, 4335, 4335, 4335, 4335, 4330, 4330, 4330)
1 + ((x1-1) %% 2)
#>   1 1 1 1 1 1 1 1 2 2 2
x3 <- c(4463,4463,4463,4463,4335,4335,4335,4335,4330,4330,4330)
identical(x1,x3)
#>  TRUE
``````

Gracias , funciono perfecto  This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.