简体   繁体   English

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

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

I am new to R programming and completely stuck in finding a solution for below problem. 我是R编程的新手,完全陷于寻找以下问题的解决方案。

I have a data set 'full_data'(near to 80 variables) but short as : 我有一个数据集“ 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

I want to write a single function in r to compute a score for these 3 customers based on a weightage as: /* this code is not working*/ 我想在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)))
)

So my final outcome for example CustomerScore is a value out of 100 based on weightage applied to each category.in the above code Customer grade:total weight:30(if loyal--30,normal--20,else--0) policy count:weight:30[in case elobrated can have more values but total wt is 30] Reach ratio weight:40[eg if >80--40 ,>40 && <80--20...] 因此,例如,我的最终结果CustomerScore是基于应用于每个类别的权重得出的100的值。在上述代码中,客户等级:总重量:30(如果为loyal--30,normal--20,else--0) count:weight:30 [如果被散布的可以有更多值,但总wt为30]达到比率weight:40 [例如,如果> 80--40,> 40 && <80--20 ...]

How to implement it efficiently in R? 如何在R中有效地实现它?

Any suggestions and ideas are welcomed!! 任何建议和想法都欢迎!!

Thank you so much !! 非常感谢 !!

We don't need to loop through the rows. 我们不需要遍历所有行。 This can be vectorized. 这可以向量化。 Based on the logic used in the OP's ifelse statements 基于OP的ifelse语句中使用的逻辑

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

Try this: 尝试这个:

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