2016-09-06 42 views
0

我有以下星火据帧:如何使用适用于找到每个组中最大SparkR

agent_product_sale=data.frame(agent=c('a','b','c','d','e','f','a','b','c','a','b'), 
         product=c('P1','P2','P3','P4','P1','p1','p2','p2','P2','P3','P3'), 
         sale_amount=c(1000,2000,3000,4000,1000,1000,2000,2000,2000,3000,3000)) 

RDD_aps=createDataFrame(sqlContext,agent_product_sale) 

    agent product sale_amount 
1  a  P1  1000 
2  b  P1  1000 
3  c  P3  3000 
4  d  P4  4000 
5  d  P1  1000 
6  c  P1  1000 
7  a  P2  2000 
8  b  P2  2000 
9  c  P2  2000 
10  a  P4  4000 
11  b  P3  3000 

我需要组星火数据帧由代理人并为每个代理找到最高sale_amount

产品
 agent most_expensive 
     a   P4   
     b   P3     
     c   P3   
     d   P4   

我用下面的代码,但它会返回最大sale_amount每个代理

schema <- structType(structField("agent", "string"), 
structField("max_sale_amount", "double")) 

result <- gapply(
RDD_aps, 
c("agent"), 
function(key, x) { 
y <- data.frame(key,max(x$sale_amount), stringsAsFactors = FALSE) 
}, schema) 
+0

尝试用'which.max' – akrun

+0

或者可以是'的gD < - AGG(GROUPBY(RDD_aps,RDD_aps $剂); AGG(排列(GD,递减(GD $ sale_amount)),most_expensive =第一(gD $ product))'(未测试) – akrun

+0

我可能是错的,但是你可以在'arrange'之后再次调用'groupBy'# – akrun

回答

0

与tapply()或聚集(),您可以一组

agent_product_sale=data.frame(agent=c('a','b','c','d','e','f','a','b','c','a','b'), 
     +        product=c('P1','P2','P3','P4','P1','p1','p2','p2','P2','P3','P3'), 
     +        sale_amount=c(1000,2000,3000,4000,1000,1000,2000,2000,2000,3000,3000)) 


tapply(agent_product_sale$sale_amount,agent_product_sale$agent, max) 
       a b c d e f 
      3000 3000 3000 4000 1000 1000 



aggregate(agent_product_sale$sale_amount,by=list(agent_product_sale$agent), max) 
      Group.1 x 
     1  a 3000 
     2  b 3000 
     3  c 3000 
     4  d 4000 
     5  e 1000 
     6  f 1000 

骨料返回data.frame中发现的最大值和typply一个数组,你的,你喜欢什么,继续与工作结果。

1
ar1 <- arrange(RDD_aps,desc(RDD_aps$sale_amount)) 
collect(summarize(groupBy(ar1,ar1‌​$agent),most_expensi‌​ve=first(ar1$product‌​))) 
相关问题