How to create sequential index value for binary column assigning 0 to FALSE values in data.table object in R?


To create sequential index value for binary column assigning 0 to FALSE values in data.table object in R, we can follow the below steps: −

  • First of all, create a data.table object with binary column.

  • Then, use rle function along with sequence and lengths function to create sequential index column.

Example

Create the data.table object

Let’s create a data.table object as shown below −

library(data.table)
x<-sample(c(TRUE,FALSE),25,replace=TRUE)
DT<-data.table(x)
DT

Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

     x
1:  FALSE
2:  TRUE
3:  FALSE
4:  FALSE
5:  FALSE
6:  TRUE
7:  FALSE
8:  FALSE
9:  FALSE
10: FALSE
11: TRUE
12: TRUE
13: FALSE
14: FALSE
15: TRUE
16: TRUE
17: FALSE
18: TRUE
19: TRUE
20: TRUE
21: TRUE
22: TRUE
23: TRUE
24: FALSE
25: TRUE
     x

Create sequential index column

Using rle function along with sequence and lengths function to create sequential index column for column x in data.table object DT −

library(data.table)
x<-sample(c(TRUE,FALSE),25,replace=TRUE)
DT<-data.table(x)
DT$Index<-with(rle(DT$x),sequence(lengths)*DT$x)
DT

Output

     x    Index
1:  FALSE  0
2:  TRUE   1
3:  FALSE  0
4:  FALSE  0
5:  FALSE  0
6:  TRUE   1
7:  FALSE  0
8:  FALSE  0
9:  FALSE  0
10: FALSE  0
11: TRUE   1
12: TRUE   2
13: FALSE  0
14: FALSE  0
15: TRUE   1
16: TRUE   2
17: FALSE  0
18: TRUE   1
19: TRUE   2
20: TRUE   3
21: TRUE   4
22: TRUE   5
23: TRUE   6
24: FALSE  0
25: TRUE   1
     x   Index

Updated on: 09-Nov-2021

42 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements