If the text string contains something, then return something to R

I have df:

Product                                   Category   
Bill Payment for Torrent Power Limited    
Recharge of Videocon d2h DTH              
Bill Payment of Airtel Mobile
Recharge of Idea Mobile

Now, if the line contains "Payment payment" and "Mobile", then I want to mark its category as "Postpaid", and if the line contains "Recharge" and "Mobile", I want to mark it as "Prepaid".

I am new to R, so the easiest way would be appreciated.

The result should be

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
+4
source share
2 answers

grep, "Product" "Bill Payment/Mobile" ( "i1" ) "Recharge/Mobile" ( "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

+3

- , :

indx <- (grepl('Bill Payment', df1$Product) & grepl('Mobile', df1$Product)) + 
  (grepl('Recharge', df1$Product) & grepl('Mobile', df1$Product))*2 + 1L

df1$category <- c(NA, "Postpaid", "Prepaid")[indx]

:

> df1
                                 Product category
1 Bill Payment for Torrent Power Limited     <NA>
2           Recharge of Videocon d2h DTH     <NA>
3          Bill Payment of Airtel Mobile Postpaid
4                Recharge of Idea Mobile  Prepaid

, , @akrun:

indx <- grepl('.*Bill Payment.*Mobile.*', df1$Product) + 
  grepl('.*Recharge.*Mobile.*', df1$Product)*2 + 1L

@nicola :

tmp <- grepl('Mobile', df1$Product)
indx <- (grepl('Bill Payment', df1$Product) & tmp) + (grepl('Recharge', df1$Product) & tmp)*2 + 1L
+3

Source: https://habr.com/ru/post/1626333/


All Articles