繁体   English   中英

如何包括应用和功能以及多个ifelse条件

[英]How to include apply and function together with multiple ifelse condit

我是R编程的新手,完全陷于寻找以下问题的解决方案。

我有一个数据集“ full_data”(接近80个变量),但简称为:

CustomerID   ReachRatio CustomerGrade  PolicyCount
1             10          Loyal         2
2             40          Normal        6
3             80          VIP           11
4             100         Normal        7

CustomerID: sequence of unique ID
Reach :a score out of 100 for customer based on contact details
CustomerGrade: It has label as 'Normal','VIP','Loyal' or 'To be   calculated','NA' and 'Uncalculated' etc
PolicyCount:No of policy brought by customer in a timeframe so >5 is good

我想在r中编写一个函数来根据权重为这3个客户计算得分,因为:/ *此代码不起作用* /

full_data$CustomerScore = apply(full_data,1,function(row)
  (((ifelse(row["CustomerGrade"]=='LOYAL',1,0)*30)+
      (ifelse(row["CustomerGrade"]=='NORMAL',1,0)*20)+
      (ifelse(row["PolicyCount"]>=4){ 1*30})+
      (ifelse(row["ReachRatio"]>=40 && row["ReachRatio"]<=80,1,0)*40)))
)

因此,例如,我的最终结果CustomerScore是基于应用于每个类别的权重得出的100的值。在上述代码中,客户等级:总重量:30(如果为loyal--30,normal--20,else--0) count:weight:30 [如果被散布的可以有更多值,但总wt为30]达到比率weight:40 [例如,如果> 80--40,> 40 && <80--20 ...]

如何在R中有效地实现它?

任何建议和想法都欢迎!!

非常感谢 !!

我们不需要遍历所有行。 这可以向量化。 基于OP的ifelse语句中使用的逻辑

with(df1, sum(30*(CustomerGrade =='Loyal')+
              20*(CustomerGrade == 'Normal') + 
              30*(PolicyCount >=4) + 
              40*(ReachRatio>=40 & ReachRatio <=80)))

尝试这个:

apply(X = df,MARGIN = 1,function(row){
    ifelse(row["CustomerGrade"]=='Loyal',30,0)+
    ifelse(row["CustomerGrade"]=='Normal',20,0)+
    ifelse(row["PolicyCount"]>=4,30,0)+
    ifelse(row["ReachRatio"]>=40 && row["ReachRatio"]<=80,20,0)+                                  
    ifelse(row["ReachRatio"]>80,40,0)})

#[1]30 70 40 50

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM