Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

r - 如何按多个列对数据框进行排序(How to sort a dataframe by multiple column(s))

I want to sort a data.frame by multiple columns.

(我想按多个列对data.frame进行排序。)

For example, with the data.frame below I would like to sort by column z (descending) then by column b (ascending):

(例如,对于下面的data.frame,我想按z列(降序)然后按b列(升序)排序:)

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
  ask by Christopher DuBois translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

(您可以直接使用order()函数,而无需借助附加工具-参见这个更简单的答案,该答案在example(order)代码顶部使用了一个技巧:)

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.

(大约2年后编辑:只是被问到如何通过列索引来做到这一点。)

The answer is to simply pass the desired sorting column(s) to the order() function:

(答案是将所需的排序列简单地传递给order()函数:)

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).

(而不是使用列名(和with()可以更容易/更直接地访问)。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...