简体   繁体   中英

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.

I have a data set 'full_data'(near to 80 variables) but short as :

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*/

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...]

How to implement it efficiently in 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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