string 在字符串键 `order(-x,v)` 上按降序对 data.table 中的行进行排序会在 data.table 1.9.4 或更早版本上出现错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12353820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:35:13  来源:igfitidea点击:

Sort rows in data.table in decreasing order on string key `order(-x,v)` gives error on data.table 1.9.4 or earlier

rstringsortingdata.tablekey

提问by nhern121

Let's say I have the following data.tablein R:

比方说,我有以下data.tableR

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

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

我想按两列(比如列xv)排序。我用过这个:

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

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

但是现在,我想按x(按降序)对其进行排序并具有以下代码:

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

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?

因此,我认为这个错误是由于class(DT$x)=character. 你能给我任何建议来解决这个问题吗?

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(x,decreasing=TRUE)],但我想知道同时使用两种方式(有些减少,有些增加)按几列排序的语法。

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?

注意,如果使用DT[order(-y,v)]结果没问题,但如果使用DT[order(-x,v)]则出现错误。所以,我的问题是:如何解决这个错误?

回答by Matthew Plourde

Update

更新

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

data.tablev1.9.6+ 现在支持 OP 的原始尝试,不再需要以下答案。



You can use DT[order(-rank(x), y)].

您可以使用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

回答by James

You can only use -on the numeric entries, so you can use decreasing and negate the ones you want in increasing order:

您只能-在数字条目上使用,因此您可以按递增顺序使用递减和否定您想要的条目:

DT[order(x,-v,decreasing=TRUE),]
      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

回答by Pankil Shah

DT[order(-x)]works as expected. I have data.table version 1.9.4. Maybe this was fixed in a recent version.
Also, I suggest the setorder(DT, -x)syntax in keeping with the set*commands like setnames, setkey

DT[order(-x)]按预期工作。我有 data.table 版本 1.9.4。也许这是在最近的版本中修复的。
另外,我建议setorder(DT, -x)使用符合set*命令的语法,例如setnamessetkey