在data.table(R)中排序行 [英] Sort rows in data.table (R)

查看:1015
本文介绍了在data.table(R)中排序行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在 R 中有以下 data.table

  library(data.table)
  DT = data.table(x=rep(c("b","a","c"),each=3), y=c(1,3,6), v=1:9)

我想通过两列来排序(例如 x v )。我使用这个:

I want to order it by two columns (say columns x and v). I used this:

 DT[order(x,v)] # sorts first by x then by v (both in ascending order)

但现在,我想通过 x (以递减顺序),并具有以下代码:

But now, I want to sort it by x (in decreasing order) and have the following code:

  DT[order(-x)] #Error in -x : invalid argument to unary operator

因此,我认为这个错误是由于 class(DT $ x)= character

Therefore, I think this error is due to the fact that class(DT$x)=character. Could you give me any suggestion in order to solve this issue?

我知道我可以使用 DT [order(x,decrease = TRUE)] ,但我想知道使用两种方法(一些减少,一些增加)同时对多列进行排序的语法。

I know I can use DT[order(x,decreasing=TRUE)], but I want to know the syntax to sort by several columns using both ways (some decreasing, some increasing) at the same time.

请注意,如果您使用 DT [order(-y,v)] ,结果是确定,你使用 DT [order(-x,v)] 有一个错误。因此,我的问题是:如何解决此错误?

Note that if you use DT[order(-y,v)] the result is ok, but if you use DT[order(-x,v)] there is an error. So, my question is: how to solve this error?

推荐答案

更新



data.table 现在支持OP的原始尝试,并且不再需要以下答案。

Update

data.table now supports OP's original attempt and the following answer is no longer necessary.

您可以使用 DT [order(-rank(x),y​​)]

   x y v
1: c 1 7
2: c 3 8
3: c 6 9
4: b 1 1
5: b 3 2
6: b 6 3
7: a 1 4
8: a 3 5
9: a 6 6

这篇关于在data.table(R)中排序行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆