If a text string contains something then return something in R -
consider have df
:
product category bill payment torrent power limited recharge of videocon d2h dth bill payment of airtel mobile recharge of idea mobile
now if string contains "bill payment" , "mobile" both want tag category "postpaid" , if string contains "recharge" , "mobile" want tag "prepaid".
i beginner in r easiest way appreciated .
result should be
product category bill payment torrent power limited na recharge of videocon d2h dth na bill payment of airtel mobile postpaid recharge of idea mobile prepaid
we can use grep
find index of 'product' both 'bill payment/mobile' ('i1') or 'recharge/mobile' ('i2'). after initializing 'category' na, replace elements based on index 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"
or more compact (that works example) option
i1 <- grepl('.*bill payment.*mobile.*', df1$product) i2 <- grepl('.*recharge.*mobile.*', df1$product)
and ifelse
Comments
Post a Comment