How to change the row order in an R data frame?

R ProgrammingServer Side ProgrammingProgramming

To change the row order in an R data frame, we can use single square brackets and provide the row order at first place.

For example, if we have a data frame called df that contains 10 rows then we can change the row order by using the command given below −

df[c(6:8,2,5,9,10,1,3:4),]

Check out the below examples to understand how it works.

Example 1

Following snippet creates a sample data frame −

x1<-rnorm(20,2)
x2<-rnorm(20,2)
df1<-data.frame(x1,x2)
df1

The following dataframe is created −

       x1        x2
1   3.0461851  1.8743169
2   0.9453059  3.8422947
3   2.4122103  2.5408842
4   1.3128584  1.1767217
5   3.4074574  1.9252181
6   1.9481946  3.6743418
7   0.3099514  1.1913972
8   3.3114028  2.3571951
9   3.3503635  2.3842746
10  1.0158586  1.5063259
11  1.3298287  1.4684843
12  2.6752537  1.9683690
13  1.1291064  2.4145713
14 -0.2177409  2.0065808
15  2.4812767  3.1936923
16  3.1920233  1.2045429
17  0.3469155  2.5212239
18  2.6807522  1.7309279
19  2.4361746  2.7317351
20  1.7637194  0.2819075

To change the order of rows in df1, add the following code to the above snippet −

x1<-rnorm(20,2)
x2<-rnorm(20,2)
df1<-data.frame(x1,x2)
df1[c(10:1,20:11),]

Output

If you execute all the above given snippets as a single program, it generates the following output −

          x1     x2
10  1.0158586  1.5063259
9   3.3503635  2.3842746
8   3.3114028  2.3571951
7   0.3099514  1.1913972
6   1.9481946  3.6743418
5   3.4074574  1.9252181
4   1.3128584  1.1767217
3   2.4122103  2.5408842
2   0.9453059  3.8422947
1   3.0461851  1.8743169
20  1.7637194  0.2819075
19  2.4361746  2.7317351
18  2.6807522  1.7309279
17  0.3469155  2.5212239
16  3.1920233  1.2045429
15  2.4812767  3.1936923
14 -0.2177409  2.0065808
13  1.1291064  2.4145713
12  2.6752537  1.9683690
11  1.3298287  1.4684843

Example 2

Following snippet creates a sample data frame −

y1<-rpois(20,2)
y2<-rpois(20,5)
y3<-rpois(20,4)
df2<-data.frame(y1,y2,y3)
df2

The following dataframe is created −

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

To change the order of rows in df2, add the following code to the above snippet −

y1<-rpois(20,2)
y2<-rpois(20,5)
y3<-rpois(20,4)
df2<-data.frame(y1,y2,y3)
df2[c(2,5,7,4,1,11,12,17,14,15,13,8,9,10,6,3,18,20,19,16),]

Output

If you execute all the above given snippets as a single program, it generates the following output −

   y1 y2 y3
2  2  5  7
5  5  3  4
7  3  4  2
4  1  5  7
1  2 11  3
11 4  3  3
12 0  5  2
17 1  6  5
14 3  9  2
15 1  6  5
13 3  3  2
8  2  3  3
9  0  5  8
10 2  7  3
6  1  2  2
3  2  3  6
18 6  8  6
20 2  4  2
19 1  6  5
16 2  5  5
raja
Published on 11-Nov-2021 06:00:02
Advertisements