【发布时间】:2015-01-25 07:04:44
【问题描述】:
我有一个数据框,其中主要列是:"source" 和 "Medium"。我需要根据"source" 和"Medium" 的值在名为"Campanas1" 的新列上分配"value"。
问题是:
使用我的代码(见下文)时,我的 col "contentGroupUniqueViews1" 的值与原始数据框不匹配。而且代码有点混乱(不紧凑)。
有没有办法:
在 data.frame 中工作,并应用一系列 ifelse 条件以在新列中输出结果? 我不想子集化然后重新加入,因为它存在重复行的高风险。
有没有更简单的方法在新列中进行 ifelse 搜索和替换? 或者至少这样做,所以我的价值观与原始价值观相匹配?我认为问题出在推荐的正则表达式中,但我现在没有看到。
这些是我的步骤:
- 多个条件的子集(结合这 2 列)。
- 使用我需要的新值创建一个新列。例如
If "souce" == "google" and "Medium" == organic" then "Búsquedas"。 - 我将这些子集放入新变量中:
Directo、Búsquedas、Adwords、Social_Media、Email、Referencias、RRSS。 - 然后使用
rbind连接所有子集以重新创建原始子集。
这是我的代码:
Directo <- subset(x = Total_Content, grepl("\\(direct\\)", source))
Directo$Campanas1 <- "Directo"
Búsquedas <- subset(x = Total_Content, grepl("google", source) & grepl("organic", Medium))
Búsquedas$Campanas1 <- "Búsquedas"
Adwords <- subset(Total_Content, grepl("google", source) & grepl("cpc", Medium) | grepl("cpv", Medium))
Adwords$Campanas1 <- "Adwords"
Social_Media <- subset(Total_Content, grepl(".*faceb.*", source) | grepl("social\\-media", Medium))
Social_Media$Campanas1 <- "Social Media"
Email <- subset(Total_Content, grepl(".*mail.*", source) | grepl(".*mail.*", Medium))
Email$Campanas1 <- "Email"
RRSS <- subset(Total_Content, grepl(".*terra.*", source) | grepl("elcomercio", source)| grepl("diario16", source)| grepl(".*laprensa.*", source))
RRSS$Campanas1 <- "RRSS"
Referencias <- subset(Total_Content, grepl(".*esp.*", source) & !grepl(".*faceb.*", source) & !grepl(".*mail.*", source) & !grepl(".*comercio.*", source) & !grepl(".*prensa.*", source) & !grepl(".*diario.*", source) & !grepl(".*terra.*", source) & grepl("referral", Medium))
Referencias$Campanas1 <- "Referencias"
Total <- rbind(Directo,Búsquedas,Adwords, Social_Media, Email, Referencias, RRSS)`
【问题讨论】: