我搜索最好的方法(我没有在当前的api中找到这一点,但可能是我弄错了)来计算像IndexedSeq这样的scala集合的不同类型的排名(比如R:http://stat.ethz.ch/R-manual/R-devel/library/base/html/rank.html中的不同策略)。
val tabToRank = IndexedSeq(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5)例如,“一级战略”等于第一次获胜,返回。
tabToRank.rank("first")
# return (4,1,6,2,7,11,3,10,8,5,9)例如,我有一个研究案例:如果在模拟的最后状态有一个具有人口的城市列表(像tabToRank这样的向量数据),我需要按等级对城市进行排序,以绘制类似于“按人口划分的城市的等级”的图形,该图形等于众所周知的等级大小分布(img的src):

发布于 2012-10-11 14:51:55
对于城市数据,你想
citipop.sortBy(x => -x).zipWithIndex.map(_.swap)首先首先对种群进行排序(缺省值是最小的,所以我们对负值进行排序),然后对它们进行编号,然后得到第一位和第二位。
然而,Scala没有内置的统计库。通常,您必须知道自己想要做什么,并且自己动手,或者使用Java库(例如)。
发布于 2012-10-11 15:11:06
下面是一段代码,它完成了您给出的示例:
object Rank extends App {
val tabToRank = IndexedSeq(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5);
def rank[A](input: Seq[A])(implicit ord: Ordering[A]): Seq[Int] = {
// transform to a pair of value/index
val withIndices: Seq[(A,Int)] = input.zipWithIndex;
// sort by the values
val sorted: Seq[(A,Int)] = withIndices.sortBy(_._1);
// keep only the indices
val indices = sorted.map(_._2);
// create the inverse permutation
val r = new collection.mutable.ArraySeq[Int](indices.size);
for((i,j) <- indices.zipWithIndex)
r(i) = j;
return r;
}
println(rank(tabToRank));
}它:
(注意,它从0开始计算,而不是从1开始计算,基本上所有编程语言都是这样做的。)
我不明白把它纳入其中的其他东西(策略)。
https://stackoverflow.com/questions/12840399
复制相似问题