簡體   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