How to add a column in an R data frame with consecutive numbers?


Addition of a column with consecutive might have different objectives such as getting the sequence of numbers, representing serial numbers, representing ids, identification of each row, or a variable. We can use the sequence starting from any number up to the number of rows if we know the number of rows for this purpose.

Example1

Consider the below data frame:

Live Demo

> x1<-rnorm(20,5,1.12)
> x2<-rnorm(20,5,0.34)
> df1<-data.frame(x1,x2)
> df1

Output

     x1       x2
1 6.137898 5.203712
2 5.283467 5.057344
3 5.873749 4.907388
4 7.628762 5.012650
5 4.134700 4.988379
6 5.340686 4.684900
7 5.126999 4.821752
8 3.722762 4.974044
9 4.097969 5.284176
10 4.249122 4.503324
11 5.511502 5.355315
12 5.826045 4.853419
13 4.947602 5.512752
14 7.174369 5.320503
15 4.671888 5.100163
16 3.777945 4.893680
17 3.591266 4.715214
18 4.270032 4.776928
19 6.913433 4.828765
20 4.619279 5.138295

Adding a column of consecutive numbers:

Example

> df1$consecutive_numbers<-1:nrow(df1)
> df1

Output

  x1 x2 consecutive numbers
1 6.137898 5.203712    1
2 5.283467 5.057344    2
3 5.873749 4.907388    3
4 7.628762 5.012650    4
5 4.134700 4.988379    5
6 5.340686 4.684900    6
7 5.126999 4.821752    7
8 3.722762 4.974044    8
9 4.097969 5.284176    9
10 4.249122 4.503324  10
11 5.511502 5.355315  11
12 5.826045 4.853419  12
13 4.947602 5.512752  13
14 7.174369 5.320503  14
15 4.671888 5.100163  15
16 3.777945 4.893680  16
17 3.591266 4.715214  17
18 4.270032 4.776928  18
19 6.913433 4.828765  19
20 4.619279 5.138295  20

Example2

Live Demo

> y1<-rpois(20,5)
> y2<-rpois(20,8)
> df2<-data.frame(y1,y2)
> df2

Output

 y1 y2
1 4 7
2 11 7
3 5 5
4 3 8
5 6 5
6 4 8
7 6 6
8 2 10
9 1 8
10 6 6
11 6 5
12 2 10
13 4 3
14 1 12
15 5 9
16 4 8
17 5 8
18 4 2
19 6 10
20 4 8

Adding a column of consecutive numbers:

Example

> df2$consecutive_numbers<-101:120
> df2

Output

 y1 y2 consecutive numbers
1 4 7     101
2 11 7    102
3 5 5     103
4 3 8     104
5 6 5     105
6 4 8     106
7 6 6     107
8 2 10    108
9 1 8     109
10 6 6    110
11 6 5    111 
12 2 10   112
13 4 3    113
14 1 12   114
15 5 9    115
16 4 8    116
17 5 8    117
18 4 2    118
19 6 10   119
20 4 8    120

Updated on: 23-Nov-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements