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


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

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

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

Example

Create the data frame

Let’s create a data frame as shown below −

x<-sample(c(TRUE,FALSE),25,replace=TRUE)
df<-data.frame(x)
df

Output

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

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

Create sequential index column

Using rle function along with sequence and lengths function to create sequential index column for column x in data frame df −

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

Output

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

Updated on: 11-Nov-2021

140 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements