This is one of the difficulties I encountered when I was making an R script for a sampling task in a project. First I thought this would be a simple problem, and apply(x, 2, sort) might be OK. Later I found it was wrong:
> a
[,1] [,2]
[1,] -14 11
[2,] 1 5
[3,] 1 2
[4,] 1 3
[5,] -2 -20
> apply(a,2,sort)
[,1] [,2]
[1,] -14 -20
[2,] -2 2
[3,] 1 3
[4,] 1 5
[5,] 1 11
Apparently the data structure was destroyed. I want to sort the matrix by a column (or several columns), but apply(x, 2, sort) sorts all the columns respectively. Of course a simple function sort() will return a more “terrible” result.
The correct way is to use the function order(), which returns a permutation which rearranges its first argument into ascending or descending order, but order() alone still can’t solve the problem. Just compare
> a[order(a[, 1]), ]
[,1] [,2]
[1,] -14 11
[2,] -2 -20
[3,] 1 5
[4,] 1 2
[5,] 1 3
with
> a[order(a[ ,1], a[ ,2]), ]
[,1] [,2]
[1,] -14 11
[2,] -2 -20
[3,] 1 2
[4,] 1 3
[5,] 1 5
Today I looked up for this question in “R FAQ” and easily found it. It seems that I still lack the habit of searching the R site.
赞赏
作为一名没有固定工作的自由职业者,我非常感谢您通过捐赠的方式来支持我的写作和开源软件开发。当然,捐赠纯属自愿。无论金额多少,都是一片诚挚的心意。支付方式如下:
| 微信 | ← 奋力支开它俩 → | 支付宝 |
|---|---|---|
![]() |
其它爱心通道 ↓ Venmo: @yihui_xie Zelle: xie@yihui.name PayPal: xie@yihui.name |
![]() |
若使用 Venmo/Zelle/Paypal,请添加备注“gift”或“donation”,以免捐赠被视为我的可税收入。若使用 Paypal,支付类型请选 Family and Friends,而不要选 Goods and Services。
在不影响生活的前提下,我会将收到的捐赠以尽量大的比例回馈给开源社区和慈善机构。作为参考,2024-25 年间我共收到约三万美元捐赠,完税后我转手捐出了一万五千美元。

