How to sort a column of data.table object in ascending order using column name stored in a vector in R?

R ProgrammingServer Side ProgrammingProgramming

Sorting a column of data.table object can be done easily with column number but sorting with column name is different. If a column name is stored in a vector and we want to sort a column of data.table object in ascending order using this name then order function will be used with single and double square brackets as shown in the below examples.

Loading data.table package and creating a data.table object −

Example

library(data.table)
x1<-rpois(20,1)
x2<-rpois(20,5)
DT1<-data.table(x1,x2)
DT1

Output

    x1 x2
1:  1  3
2:  1  6
3:  2  3
4:  0  7
5:  1  8
6:  0  5
7:  1  3
8:  0  4
9:  1  2
10: 0  6
11: 0  5
12: 0  4
13: 2  6
14: 0  6
15: 2  0
16: 0  2
17: 1  6
18: 0  6
19: 2  7
20: 2  2

Column_for_sorting<-"x2"

Sorting DT1 using Column_for_sorting −

Example

DT1[order(DT1[[Column_for_sorting]])]

Output

   x1  x2
1:  2  0
2:  1  2
3:  0  2
4:  2  2
5:  1  3
6:  2  3
7:  1  3
8:  0  4
9:  0  4
10: 0  5
11: 0  5
12: 1  6
13: 0  6
14: 2  6
15: 0  6
16: 1  6
17: 0  6
18: 0  7
19: 2  7
20: 1  8

Example

y1<-rnorm(20)
y2<-rnorm(20)
DT2<-data.table(y1,y2)
DT2

Output

        y1           y2
1:   0.3499126    1.6988660
2:  -0.6970935   -1.2961417
3:   0.1244235    1.1192189
4:  -1.0639993    0.2504188
5:  -0.5714189    0.9772097
6:   1.3096543    1.5397439
7:   0.1163726   -2.8518334
8:  -1.2941302    0.6353213
9:  -0.4853220   -0.2274419
10: -0.3999413   -0.4259027
11:  2.9027999    0.2589249
12:  1.6724920   -1.2572220
13:  0.8792422   -0.5715381
14:  1.3257716    1.4083895
15: -0.9301681    0.1565980
16: -1.3777834    0.3630332
17:  0.1585897   -1.7692727
18: -2.7972968   -0.3854796
19: -1.4035229   -0.9016175
20:  1.4411729    0.1969444

Column_for_sorting<-"y1"

Sorting DT2 using Column_for_sorting −

Example

DT2[order(DT2[[Column_for_sorting]])]

Output

        y1          y2
1:  -2.7972968   -0.3854796
2:  -1.4035229   -0.9016175
3:  -1.3777834    0.3630332
4:  -1.2941302    0.6353213
5:  -1.0639993    0.2504188
6:  -0.9301681    0.1565980
7:  -0.6970935   -1.2961417
8:  -0.5714189    0.9772097
9:  -0.4853220   -0.2274419
10: -0.3999413   -0.4259027
11:  0.1163726   -2.8518334
12:  0.1244235    1.1192189
13:  0.1585897   -1.7692727
14:  0.3499126    1.6988660
15:  0.8792422   -0.5715381
16:  1.3096543    1.5397439
17:  1.3257716    1.4083895
18:  1.4411729    0.1969444
19:  1.6724920   -1.2572220
20:  2.9027999    0.2589249
raja
Published on 10-Feb-2021 15:20:59
Advertisements