grep函数,具有混合字向量的多个术语

时间:2017-11-01 01:06:57

标签: r function grep shiny

TEST<- function(x){
test <- data1[grep(x, data1$REMARKS),]
test1 <- test%>%
group_by(date)%>%
summarise(tot = sum(TOTAL, na.rm = T))
y <- ggplot(test1, aes(date, tot)) + geom_point() + geom_line()
return(y)
}

这是我正在使用的函数...数据集中有一个包含多个单词的向量。基本上我想要做的是创建一个函数(可能在Shiny中),我可以在其中输入多个单词,这将从向量中提取行以进行分析。这有可能与grep功能?上述功能适用于一个单词。感谢。

1 个答案:

答案 0 :(得分:1)

一种可能性是基于多个单词构建正则表达式搜索表达式。看看下面的例子:

# Sample words
words <- c("word1", "word2", "word3");

# Construct regexp expression from list of words
makeRegExpr <- function(words) {
    return(sprintf("(%s)",paste(words, collapse = "|")))
}
makeRegExpr(words);
#[1] "(word1|word2|word3)"

然后,您可以在函数中使用makeRegExpr(words)来过滤与任何这些词匹配的条目。

TEST <- function(words) {
    test <- data1[grep(makeRegExpr(words), data1$REMARKS), ]
    ...
}