2016-01-28 34 views
3

考慮我有一個df如果文本字符串包含那麼就有R中返回的東西

Product         Category 
Bill Payment for Torrent Power Limited  
Recharge of Videocon d2h DTH    
Bill Payment of Airtel Mobile 
Recharge of Idea 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 
+0

DF $類別[grepl(」 Bill \\ sPayment「)&grepl(」Mobile「)] < - 」Postpaid「 –

回答

3

我們可以用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

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 
+0

即將發佈這些內容,但我想您應該先儲存'grepl('Mobile',df1 $ Product)'不要重複兩次相同的操作。 – nicola

+0

@nicola我認爲這是不可能的,因爲其他兩個短語匹配但沒有匹配'Mobile'的情況應排除 – Jaap

+0

我在說'tmp <-grepl('Mobile',df1 $產品)'然後'(grepl('Bill Payment',df1 $ Product)&tmp)+ ...'。猜猜我說得很糟糕。 – nicola

相關問題