根据其他三列中的值设置R列中的值

我有一些原始数据看起来像这样,我从R中导出后,在Excel中手动添加Segment列。

原始数据拉入Excel

原始数据拉入Excel

我想在R中编写代码,为我添加Segment。

数据说明…

ID: Random distinct numbers flag: Yes or No Period: 0-12 Mths or 12-24 Mths Spend Group: High, Medium or Low 

规则…

 Flag = Yes Period = 0-12 Mths Spend Group = High Then Segment = G01 Flag = Yes Period = 0-12 Mths Spend Group = Medium Then Segment = G02 Flag = Yes Period = 0-12 Mths Spend Group = Low Then Segment = G03 Flag = Yes Period = 12-24 Mths Spend Group = High Then Segment = G04 

…等等,直到所有variables都被计入

我希望代码在每次处理数据时识别差异,例如,标志不总是为“是”或“否”。有时对于每一行都是“是”。

我的完整数据集概述如下图所示。

摘要数据

摘要数据

你将如何开始在R中编码?

为了扩展我上面的评论(对不起,我很着急),我build议让你的规则在csv(或只是定义为一个数据框架,但如果他们要改变csv可能是最简单的),并阅读作为一个单独的data.frame例如下面。 这将使标志,期间和花费组的每个组合都与要分配给每个组合的段相关联。

假设您的数据(名称为“Unique.ID”,“flag”,“period”,“spend_group”)在df

 library(dplyr) df_withSegment <- left_join(df, rules) 

由于“flag”,“period”,“spend_group”是所有具有通用名称的列,因此将规则中的Segment的值分配给这三列的每个组合。

规则例如数据框(从csv或R)

在这里输入图像说明

在我头上合并似乎是正确的方式。

(raw_data,summary_data,by.x = c(“flag”,“period”,“cost_group”),by.y = c(“flag”,“recency”,“spend_band”))

我会用四步ifelse()

你在四个子集内引用你的数据Flag == "yes" & Recency == "0-12 Mths"Flag == "yes" & Recency == "12-24 Mths"Flag == "no" & Recency == "0-12 Mths"Flag == "no" & Recency == "12-24 Mths"并启动ifelse()调用:

 mydata$Segment[mydata$Flag == "yes" & mydata$Recency == "0-12 Mths"] <- with(mydata[mydata$Flag == "yes" & mydata$Recency == "0-12 Mths", ], ifelse(Spend Band == "High", "G01", ifelse(Spend Band == "Medium", "G02", "G03"))) mydata$Segment[mydata$Flag == "yes" & mydata$Recency == "12-24 Mths"] <- with(mydata[mydata$Flag == "yes" & mydata$Recency == "12-24 Mths", ], ifelse(Spend Band == "High", "G04", ifelse(Spend Band == "Medium", "G05", "G06"))) mydata$Segment[mydata$Flag == "no" & mydata$Recency == "0-12 Mths"] <- with(mydata[mydata$Flag == "no" & mydata$Recency == "0-12 Mths", ], ifelse(Spend Band == "High", "G07", ifelse(Spend Band == "Medium", "G08", "G09"))) mydata$Segment[mydata$Flag == "no" & mydata$Recency == "12-24 Mths"] <- with(mydata[mydata$Flag == "no" & mydata$Recency == "12-24 Mths", ], ifelse(Spend Band == "High", "G10", ifelse(Spend Band == "Medium", "G11", "G12"))) 

你将不得不改变variables名称,因为Spend Band不是一个可行的variables名在R,因此我想你的将被称为Spend_Band或类似的东西。