如何使用存储在R中的向量中的列名按升序对data.table对象的列进行排序?
使用列号对data.table对象的列进行排序很容易,但是使用列名进行排序却有所不同。如果列名称存储在向量中,并且我们希望data.table使用该名称以升序对对象列进行排序,则将在单方括号和双方括号中使用order函数,如以下示例所示。
加载data.table包并创建一个data.table对象-
示例
library(data.table)输出结果x1<-rpois(20,1)
x2<-rpois(20,5)
DT1<-data.table(x1,x2)
DT1
x1 x21: 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”
使用Column_for_sorting对DT1进行排序-
示例
DT1[order(DT1[[Column_for_sorting]])]输出结果
x1 x21: 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
示例
y1<-rnorm(20)输出结果y2<-rnorm(20)
DT2<-data.table(y1,y2)
DT2
y1 y21: 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”
使用Column_for_sorting对DT2进行排序-
示例
DT2[order(DT2[[Column_for_sorting]])]输出结果
y1 y21: -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
以上是 如何使用存储在R中的向量中的列名按升序对data.table对象的列进行排序? 的全部内容, 来源链接: utcz.com/z/314357.html