下面我寫了一個函數,它搜索矢量中的特定正則表達式。該函數始終在向量中搜索正則表達式,包括「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
你的意思'grepl(「Beer。* Wine | Wine。* Beer」,x,ignore.case = TRUE)'? –