How to renumber rows if they are unordered in R?

R ProgrammingServer Side ProgrammingProgramming

When we create a sample using inbuilt or imported data set then the numbering for selected rows as in the original data set, therefore, the numbering becomes unordered. To change this unordered numbering to a sequence say starting from one to the total number of rows in the sample, we can use 1:nrow(“sample_object_name”).

Consider the below data frame −

Example

 Live Demo

set.seed(999)
x<-rnorm(20,5,1)
y<-rnorm(20,2,0.80)
z<-rnorm(20,3,0.95)
df1<-data.frame(x,y,z)
df1

Output

      x       y          z
1 4.718260 1.0171494 2.538645
2 3.687440 2.5144355 3.008073
3 5.795184 1.7121897 1.781992
4 5.270070 2.2352285 1.944000
5 4.722694 1.0997852 3.285632
6 4.433976 2.5138125 3.262655
7 3.121342 1.1146099 1.051666
8 3.733209 1.2921277 3.013481
9 4.032250 0.7567239 3.553153
10 3.878991 1.8986568 2.967010
11 6.325464 3.9061313 2.889169
12 5.133977 2.4810209 2.387267
13 5.938749 2.1434890 4.657191
14 5.172538 2.8644252 3.347790
15 5.957650 1.8025503 2.936531
16 3.637314 0.3090104 3.268482
17 5.068335 1.7035780 3.539310
18 5.100658 2.4182942 1.784745
19 5.901345 2.4142444 3.413600
20 2.925643 0.8779913 2.462774

Taking a sample of data frame df1 −

Example

Sample1<-df1[sample(nrow(df1),10),] Sample1

Output

     x y z
 14 5.172538 2.8644252 3.347790
16 3.637314 0.3090104 3.268482
12 5.133977 2.4810209 2.387267
10 3.878991 1.8986568 2.967010
11 6.325464 3.9061313 2.889169
20 2.925643 0.8779913 2.462774
15 5.957650 1.8025503 2.936531
19 5.901345 2.4142444 3.413600
13 5.938749 2.1434890 4.657191
17 5.068335 1.7035780 3.539310

Setting the row numbers starting from 1 to total number of rows in Sample1 −

Example

row.names(Sample1)<-1:nrow(Sample1) Sample1

Output

    x          y       z
1  5.172538 2.8644252 3.347790
2  3.637314 0.3090104 3.268482
3  5.133977 2.4810209 2.387267
4  3.878991 1.8986568 2.967010
5  6.325464 3.9061313 2.889169
6  2.925643 0.8779913 2.462774
7  5.957650 1.8025503 2.936531
8  5.901345 2.4142444 3.413600
9  5.938749 2.1434890 4.657191
10 5.068335 1.7035780 3.539310

Let’s have a look at another example −

Example

 Live Demo

a<-rpois(20,5)
b<-rpois(20,2)
c<-rpois(20,10)
df2<-data.frame(a,b,c)
df2

Output

a b c
1 4 3 5
2 5 1 14
3 4 4 9
4 6 3 6
5 5 0 8
6 3 3 9
7 4 3 6
8 2 0 7
9 5 2 7
10 8 2 11
11 7 4 9
12 4 3 11
13 6 2 7
14 5 5 12
15 7 2 11
16 5 1 12
17 7 3 5
18 1 0 15
19 6 1 10
20 3 1 6

Taking a sample of df2 −

Example

Sample2<-df2[sample(nrow(df2),12),] 
Sample2

Output

 a b c
8  2 1 10
10 6 1 11
14 7 0  7
2 12 2  6
18 7 0  6
9  5 1  4
13 1 1 11
6  3 2  6
16 4 3  7
1  5 3 10
15 6 3  3
17 4 2  6

Setting the row numbers starting from 1 to total number of rows in Sample2 −

Example

row.names(Sample2)<-1:nrow(Sample2)
Sample2

Output

  a b c
1  2 1 10
2  6 1 11
3  7 0  7
4 12 2  6
5  7 0  6
6  5 1  4
7  1 1 11
8  3 2  6
9  4 3  7
10 5 3 10
11 6 3  3
12 4 2  6
raja
Published on 09-Oct-2020 15:01:33
Advertisements