如何按列排序数据框? [英] How to sort a dataframe by column(s)?
问题描述
z
(descending)然后按列 b
(升序): dd< - data 。框架(b = factor(c(Hi,Med,Hi,Low),
levels = c(Low,Med,Hi ),
x = c(A,D,A,C),y = c(8,3,9,9),
z = 1,2))
dd
bxyz
1嗨A 8 1
2医疗D 3 1
3嗨A 9 1
4低C 9 2
您可以使用 order()
函数直接而不使用附加工具 - 请参阅这个更简单的答案,它使用从示例(顺序)
代码顶部的技巧:
R> dd [with(dd,order(-z,b))]]
bxyz
4低C 9 2
2 Med D 3 1
1嗨A 8 1
3嗨A 9 1
2年后编辑:只是被问到如何通过列索引这样做。答案是简单地将所需的排序列传递给 order()
function:
R> dd [order(-dd [,4],dd [,1]),]
bxyz
4低C 9 2
2 Med D 3 1
1 Hi A 8 1
3嗨A 9 1
R>
而不是使用列的名称(和 with()
更容易/更直接的访问)。
I want to sort a data.frame by multiple columns in R. For example, with the data.frame below I would like to sort by column z
(descending) then by column b
(ascending):
dd <- data.frame(b = factor(c("Hi", "Med", "Hi", "Low"),
levels = c("Low", "Med", "Hi"), ordered = TRUE),
x = c("A", "D", "A", "C"), y = c(8, 3, 9, 9),
z = c(1, 1, 1, 2))
dd
b x y z
1 Hi A 8 1
2 Med D 3 1
3 Hi A 9 1
4 Low C 9 2
You can use the order()
function directly without resorting to add-on tools -- see this simpler answer which uses a trick right from the top of the example(order)
code:
R> dd[with(dd, order(-z, b)), ]
b x y z
4 Low C 9 2
2 Med D 3 1
1 Hi A 8 1
3 Hi A 9 1
Edit some 2+ years later: It was just asked how to do this by column index. The answer is to simply pass the desired sorting column(s) to the order()
function:
R> dd[ order(-dd[,4], dd[,1]), ]
b x y z
4 Low C 9 2
2 Med D 3 1
1 Hi A 8 1
3 Hi A 9 1
R>
rather than using the name of the column (and with()
for easier/more direct access).
这篇关于如何按列排序数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!