【发布时间】:2022-01-05 07:23:32
【问题描述】:
我可以将自定义比较函数传递给order,给定两个项目,指示哪个项目排名更高?
在我的具体情况下,我有以下列表。
scores <- list(
'a' = c(1, 1, 2, 3, 4, 4),
'b' = c(1, 2, 2, 2, 3, 4),
'c' = c(1, 1, 2, 2, 3, 4),
'd' = c(1, 2, 3, 3, 3, 4)
)
如果我们采用两个向量a 和b,则i 的第一个元素的索引a[i] > b[i] 或a[i] < b[i] 应该确定哪个向量先出现。在这个例子中,scores[['d']] > scores[['a']] 因为scores[['d']][2] > scores[['a']][2](注意scores[['d']][5] < scores[['a']][5] 无关紧要)。
比较其中两个向量可能看起来像这样。
compare <- function(a, b) {
# get first element index at which vectors differ
i <- which.max(a != b)
if(a[i] > b[i])
1
else if(a[i] < b[i])
-1
else
0
}
scores使用这个比较函数排序后的key应该是d, b, a, c。
从我找到的其他解决方案中,他们mess with the data before ordering 或介绍S3 classes and apply comparison attributes。对于前者,我看不到如何处理我的数据(也许将其转换为字符串?但是 9 以上的数字呢?),对于后者,我觉得在我的 R 包中引入一个新类只是为了比较向量而感到不舒服。而且似乎没有我想传递给order的比较器参数。
【问题讨论】:
标签: r sorting comparison