2016-08-16 65 views
0

下面我寫了一個函數,它搜索矢量中的特定正則表達式。該函數始終在向量中搜索正則表達式,包括「Beer」或「Wine」。現在我想包括我正在尋找的正則表達式(在我的例子中是「Beer and Wine」)作爲向量中的附加變量。我怎樣才能做到這一點?在drinks如何在R中的函數中包含正則表達式?

x <- c("Beer","Wine","wine","Beer","Beef","Potato","Vacation") 
drinks <- c("Beer","Wine") 
Thirsty <- function(x, drinks) { 
    Reduce("|",lapply(drinks, function(p)grepl(p,x, ignore.case = TRUE))) 
} 
y <- Thirsty(x,drinks) 
y 

lapply環上的可能性和產生邏輯向量的列表,每個飲料:

x <- c("Beer","Wine","wine","Beer","Beef","Potato","Vacation") 
Thirsty <- function(x) { 
Beer <- grepl("Beer",x, ignore.case = TRUE) 
Beer <- as.numeric(Beer == "TRUE") 
Wine <- grepl("Wine",x, ignore.case = TRUE) 
Wine <- as.numeric(Wine == "TRUE") 
Drink <- Beer + Wine 
Drink <- as.numeric(Drink == "0") 
Drink <- abs(Drink -1) 
} 
    y <- Thirsty(x) 
    y 
+0

你的意思'grepl(「Beer。* Wine | Wine。* Beer」,x,ignore.case = TRUE)'? –

回答

1

這可以用下面的代碼來完成。這些通過Reduce合併成一個單獨的向量。

1

我只想嘗試|

strings = c("Beer","Wine","wine","Beer","Beef","Potato","Vacation") 
thirstStrings = c("beer", "wine") 

matchPattern = paste0(thirstStrings, collapse = "|") #"beer|wine" 
grep(pattern = matchPattern, x = strings, ignore.case = T) 
# [1] 1 2 3 4 

來串聯匹配模式,您可以輕鬆地包裹在一個函數

Thirsty = function(x, matchStrings){ 
    matchPattern = paste0(matchStrings, collapse = "|") #"beer|wine" 
    grep(pattern = matchPattern, x = x, ignore.case = T) 
} 

Thirsty(strings, thirstStrings) # [1] 1 2 3 4 
1

這也應該工作

Thirsty = function(vec, ...) { 
    pattern = paste0(unlist(list(...)), collapse = "|") 
    stringr::str_detect(tolower(vec), pattern) 
} 

> Thirsty (x, "beer", "wine") 
[1] TRUE TRUE TRUE TRUE FALSE FALSE FALSE  
+0

它不應該是'tolower(vec)'在你的函數內。除非有一些特殊的巫術,你的'x'將引用全局變量而不是輸入值? – Choubi

+0

@Choubi,謝謝你忘了改變它 –

相關問題