考虑我有一个df
:
Product Category
Bill Payment for Torrent Power Limited
Recharge of Videocon d2h DTH
Bill Payment of Airtel Mobile
Recharge of Idea Mobile
现在,如果一个字符串包含“账单支付”和“移动”,那么我想将其类别标记为“后付费”,如果字符串包含“充值”和“移动”,我想将其标记为“预付费”。
我是 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)