0
我有一个映射器,可以发出键/值对(复合键和复合值由逗号分隔)。如何计算Spark中的多个值的平均值
例如
键: A,B,C,d 值: 1,2,3,4,5
键: A1,B1,C1,D1 值: 5,4,3,2,1
...
...
键: A,B,C,d 值: 5,4,3,2,1
我可以很容易地使用SUM reduceByKey这些值。
e.g
reduceByKey(new Function2<String, String, String>() {
@Override
public String call(String value1, String value2) {
String oldValue[] = value1.toString().split(",");
String newValue[] = value2.toString().split(",");
int iFirst = Integer.parseInt(oldValue[0]) + Integer.parseInt(newValue[0]);
int iSecond = Integer.parseInt(oldValue[1]) + Integer.parseInt(newValue[1]);
int iThird = Integer.parseInt(oldValue[2]) + Integer.parseInt(newValue[2]);
int iFourth = Integer.parseInt(oldValue[3]) + Integer.parseInt(newValue[3]);
int iFifth = Integer.parseInt(oldValue[4]) + Integer.parseInt(newValue[4]);
return iFirst + "," + iSecond + ","
+ iThird+ "," + iFourth+ "," + iFifth;
}
});
但问题是我怎么找到这些值只是一个平均水平。让我们假设我想SUM iFirst,iSecond,iThird和iFourth,但我想找到iFifth的平均值。我该怎么做?通过一个简单的键/值对,我可以使用mapValues函数,但不知道如何用我的例子做到这一点。请指教。
你可以分享你的代码,你如何解决这个使用foldByKey? –