要按升序对R数据帧的每一行进行排序,我们可以使用apply函数对列进行排序,然后对输出进行转置。例如,如果我们有一个名为df的数据帧,其中包含5列,则可以使用命令t(apply(df,1,sort))以递增的顺序对df的每一行进行排序。
考虑以下数据帧-
x1<-rpois(20,5) x2<-rpois(20,5) x3<-rpois(20,5) x4<-rpois(20,5) df1<-data.frame(x1,x2,x3,x4) df1输出结果
x1 x2 x3 x4 1 4 3 6 8 2 4 4 5 3 3 1 6 4 4 4 5 3 7 5 5 4 7 3 7 6 7 7 8 3 7 4 13 5 2 8 5 4 4 5 9 7 4 1 5 10 5 4 6 7 11 6 3 2 2 12 3 0 6 5 13 4 5 5 2 14 7 12 6 8 15 6 4 6 3 16 8 7 3 3 17 7 6 5 3 18 5 5 5 8 19 6 3 1 9 20 2 4 3 4
按升序对df1中的每一行进行排序-
t(应用(df1,1,sort))
[,1] [,2] [,3] [,4] [1,] 3 4 6 8 [2,] 3 4 4 5 [3,] 1 4 4 6 [4,] 3 5 5 7 [5,] 3 4 7 7 [6,] 3 7 7 8 [7,] 2 4 5 13 [8,] 4 4 5 5 [9,] 1 4 5 7 [10,] 4 5 6 7 [11,] 2 2 3 6 [12,] 0 3 5 6 [13,] 2 4 5 5 [14,] 6 7 8 12 [15,] 3 4 6 6 [16,] 3 3 7 8 [17,] 3 5 6 7 [18,] 5 5 5 8 [19,] 1 3 6 9 [20,] 2 3 4 4
y1<-rnorm(20) y2<-rnorm(20) y3<-rnorm(20) df2<-data.frame(y1,y2,y3) df2输出结果
y1 y2 y3 1 0.98162958 -0.2989471 -0.2254131 2 1.17064693 -1.9476458 -0.3945834 3 0.73691436 -1.8172343 -0.5653013 4 0.97507754 1.2841860 0.6290046 5 -0.84053056 1.2600141 -0.1827997 6 0.99946765 -0.7165685 0.2499400 7 0.01351743 0.2432559 0.7501626 8 0.60395966 -1.9376705 -0.6750133 9 1.92813786 -1.2536224 -0.3118962 10 -0.03692577 -0.9030202 0.9266927 11 0.60933676 0.3523446 -1.6367644 12 -0.77165402 0.6806964 -0.8524336 13 -1.62599096 2.1177609 -0.7749328 14 0.60632948 0.2074926 0.2615405 15 0.23464045 1.3825833 0.3813821 16 -0.27508014 0.6975645 -0.6448739 17 -0.30863343 0.9172400 1.6155362 18 -0.53579916 -0.5614784 0.8595362 19 -0.08786005 -1.0634296 0.9763744 20 0.66566923 0.2453712 1.1790946
按升序对df2中的每一行进行排序-
t(应用(df2,1,sort))
[,1] [,2] [,3] [1,] -0.29894710 -0.22541313 0.9816296 [2,] -1.94764575 -0.39458339 1.1706469 [3,] -1.81723426 -0.56530126 0.7369144 [4,] 0.62900459 0.97507754 1.2841860 [5,] -0.84053056 -0.18279967 1.2600141 [6,] -0.71656845 0.24994000 0.9994676 [7,] 0.01351743 0.24325586 0.7501626 [8,] -1.93767048 -0.67501331 0.6039597 [9,] -1.25362238 -0.31189625 1.9281379 [10,] -0.90302017 -0.03692577 0.9266927 [11,] -1.63676440 0.35234462 0.6093368 [12,] -0.85243362 -0.77165402 0.6806964 [13,] -1.62599096 -0.77493280 2.1177609 [14,] 0.20749255 0.26154053 0.6063295 [15,] 0.23464045 0.38138210 1.3825833 [16,] -0.64487386 -0.27508014 0.6975645 [17,] -0.30863343 0.91724003 1.6155362 [18,] -0.56147837 -0.53579916 0.8595362 [19,] -1.06342956 -0.08786005 0.9763744 [20,] 0.24537124 0.66566923 1.1790946