如何按字母顺序对 R 数据框行进行排序?
如果我们将字符串数据存储在R数据框列中,那么我们可能希望按字母顺序对数据框行进行排序。这可以借助转置函数中的apply和sort函数来完成。
例如,如果我们有一个名为df的数据框,其中包含字符串数据,则可以使用以下给定的命令按字母顺序对df进行排序-
t(apply(df,1,sort))
示例1
以下代码段创建了一个示例数据框-
x1<-sample(LETTERS[1:26],20) x2<-sample(LETTERS[1:26],20) x3<-sample(LETTERS[1:26],20) df1<-data.frame(x1,x2,x3) df1输出结果
创建以下数据框-
x1 x2 x3 1 Z L Y 2 Q W J 3 P S Z 4 U E C 5 M C K 6 H G M 7 L A I 8 F Q T 9 R T G 10 X N P 11 T I L 12 N J E 13 E X R 14 Y U N 15 W D W 16 S M F 17 B O V 18 A B U 19 I Z D 20 O F A
要按字母顺序对df1行进行排序,请将以下代码添加到上面的代码段中-
x1<-sample(LETTERS[1:26],20) x2<-sample(LETTERS[1:26],20) x3<-sample(LETTERS[1:26],20) df1<-data.frame(x1,x2,x3) t(apply(df1,1,sort))输出结果
如果您将上述所有代码作为单个程序执行,它会生成以下输出-
[,1] [,2] [,3] [1,] "L" "Y" "Z" [2,] "J" "Q" "W" [3,] "P" "S" "Z" [4,] "C" "E" "U" [5,] "C" "K" "M" [6,] "G" "H" "M" [7,] "A" "I" "L" [8,] "F" "Q" "T" [9,] "G" "R" "T" [10,] "N" "P" "X" [11,] "I" "L" "T" [12,] "E" "J" "N" [13,] "E" "R" "X" [14,] "N" "U" "Y" [15,] "D" "W" "W" [16,] "F" "M" "S" [17,] "B" "O" "V" [18,] "A" "B" "U" [19,] "D" "I" "Z" [20,] "A" "F" "O"
示例2
以下代码段创建了一个示例数据框-
y1<-sample(c("India","Russia","China"),20,replace=TRUE) y2<-sample(c("UK","USA","Egpyt"),20,replace=TRUE) y3<-sample(c("Sudan","Nepal","Croatia"),20,replace=TRUE) df2<-data.frame(y1,y2,y3) df2输出结果
创建以下数据框-
y1 y2 y3 1 India UK Nepal 2 India Egpyt Sudan 3 China USA Nepal 4 China USA Sudan 5 Russia UK Nepal 6 India Egpyt Sudan 7 India UK Croatia 8 China USA Nepal 9 India Egpyt Nepal 10 Russia UK Croatia 11 Russia UK Nepal 12 India UK Croatia 13 Russia USA Nepal 14 Russia Egpyt Nepal 15 India Egpyt Croatia 16 India Egpyt Nepal 17 China UK Nepal 18 India UK Sudan 19 India Egpyt Croatia 20 Russia USA Nepal
要按字母顺序对df2行进行排序,请将以下代码添加到上面的代码段中-
y1<-sample(c("India","Russia","China"),20,replace=TRUE) y2<-sample(c("UK","USA","Egpyt"),20,replace=TRUE) y3<-sample(c("Sudan","Nepal","Croatia"),20,replace=TRUE) df2<-data.frame(y1,y2,y3) t(apply(df2,1,sort))输出结果
如果您将上述所有代码作为单个程序执行,它会生成以下输出-
[,1] [,2] [,3] [1,] "India" "Nepal" "UK" [2,] "Egpyt" "India" "Sudan" [3,] "China" "Nepal" "USA" [4,] "China" "Sudan" "USA" [5,] "Nepal" "Russia" "UK" [6,] "Egpyt" "India" "Sudan" [7,] "Croatia" "India" "UK" [8,] "China" "Nepal" "USA" [9,] "Egpyt" "India" "Nepal" [10,] "Croatia" "Russia" "UK" [11,] "Nepal" "Russia" "UK" [12,] "Croatia" "India" "UK" [13,] "Nepal" "Russia" "USA" [14,] "Egpyt" "Nepal" "Russia" [15,] "Croatia" "Egpyt" "India" [16,] "Egpyt" "India" "Nepal" [17,] "China" "Nepal" "UK" [18,] "India" "Sudan" "UK" [19,] "Croatia" "Egpyt" "India" [20,] "Nepal" "Russia" "USA"