2017-04-21 221 views
1

我想根據一些條件搜索關鍵詞。我下面的代碼創建了一些示例數據,並試圖通過這個。它不喜歡ifelse,我相信因爲GREP實際上並沒有返回真/假,而是實際的數據。我在想我必須創建一個子集,然後將它合併回來?但是,我似乎無法在GREP子集中添加多於1個條件。多個條件關鍵字搜索

任何幫助非常感謝!

bus_name <- c('jacks wok shop' 
       ,'jacks ski shop' 
       ,'jacks wokshop' 
       ,'jacks bakery' 
       ,'jacks business' 
       ,'jims Brewery' 
       ,'jims Wok Brewery' 
) 
type <- c('restaurant' 
      ,'restaurant' 
      ,'restaurant' 
      ,'restaurant' 
      ,'office' 
      ,'store' 
      ,'building' 
) 

mydata <- data.frame(bus_name, type) 

mydata$bus_name <- as.character(mydata$bus_name) 
mydata$type <- as.character(mydata$type) 


mydata$flag <- ifelse(mydata$type == "restaurant" & mydata[grep("WOK",toupper(mydata$bus_name)),],"Wok", 
         ifelse(mydata$type == "office" & mydata[grep("BUSINESS",toupper(mydata$bus_name)),],"Business","0")) 

理想的輸出將是如下:

bus_name|type|flag 
jacks wok shop|restaurant|Wok 
jacks ski shop|restaurant 
jacks wokshop|restaurant|Wok 
jacks bakery|restaurant 
jacks business|office|Business 
jims Brewery|store 
jims Wok Brewery|building|Wok 
+0

的類型真的應該有「‘酒樓’? –

+0

對不起,那是拼錯在少數地方..固定它 –

回答

1

grepl是,如果你想邏輯值使用的功能。你需要像這樣

mydata$flag <- ifelse(mydata$type == "restaurant" & grepl("WOK",toupper(mydata$bus_name)), 
           "Wok", 
         ifelse(mydata$type == "office" & grepl("BUSINESS",toupper(mydata$bus_name)), 
           "Business","")) 
2

你必須使用grepl獲得的TRUE/FALSE的邏輯載體。您可以使用dplyr中的case_when。它比嵌套ifelse更容易閱讀。

library(dplyr) 
mydata %>% 
mutate(flag=case_when(
.$type == "restaurant" & grepl("WOK",toupper(.$bus_name)) ~ "Wok", 
.$type == "office" & grepl("BUSINESS",toupper(.$bus_name)) ~ "Business", 
                 TRUE ~ "0" 
)) 

      bus_name  type  flag 
1 jacks wok shop restaurant  Wok 
2 jacks ski shop restaurant  0 
3 jacks wokshop restaurant  Wok 
4  jacks bakery restaurant  0 
5 jacks business  office Business 
6  jims Brewery  store  0 
7 jims Wok Brewery building  0 
+0

完美的!我一直在尋找,如果可能將dplyr。偉大的作品,謝謝! –