如何在R中的函数中包含正则表达式?

时间:2016-08-16 08:11:08

标签: regex r function

下面我写了一个函数,它在向量中搜索特定的正则表达式。该函数总是搜索正则表达式,包括"啤酒"或者" Wine"在向量中。现在我想将我正在搜索的常规表达式(在我的情况下"啤酒和葡萄酒")作为附加变量包含在向量中。我怎样才能做到这一点?

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

2 个答案:

答案 0 :(得分:1)

可以使用以下代码完成此操作:

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循环遍历drinks中的各种可能性,并生成一个逻辑向量列表,每个饮料一个。这些由Reduce组合成单个向量。

答案 1 :(得分: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