考虑我有一个df
:
Product Category
Bill Payment for Torrent Power Limited
Recharge of Videocon d2h DTH
Bill Payment of Airtel Mobile
Recharge of Idea Mobile
现在,如果一个字符串同时包含“ Bill Payment”和“ Mobile”,则我要将其类别标记为“ Postpaid”,如果一个字符串包含“ Recharge”和“ Mobile”,则要将其标记为“ Prepaid”。
我是R的初学者,因此最简单的方法将不胜感激。
结果应该是
Product Category
Bill Payment for Torrent Power Limited NA
Recharge of Videocon d2h DTH NA
Bill Payment of Airtel Mobile Postpaid
Recharge of Idea Mobile Prepaid
我们可以使用grep
“帐单付款/移动”(i1)或“充值/移动”(i2)查找“产品”的索引。将“类别”初始化为NA后,我们根据索引i1和i2替换元素。
i1 <- grepl('Bill Payment', df1$Product) & grepl('Mobile', df1$Product)
i2 <- grepl('Recharge', df1$Product) & grepl('Mobile', df1$Product)
df1$Category <- NA
df1$Category[i1] <- 'Postpaid'
df1$Category[i2] <- 'Prepaid'
df1
#[1] NA NA "Postpaid" "Prepaid"
或者稍微紧凑一点(适用于示例)是
i1 <- grepl('.*Bill Payment.*Mobile.*', df1$Product)
i2 <- grepl('.*Recharge.*Mobile.*', df1$Product)
并与 ifelse
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句