如何使用dplyr过滤精确匹配的字符串

3

我有一个数据表 datatmp

    datatmp
        Code         Desc
       Z00.1 Description1
         Z00 Description2
         Z38 Description3
       Z38.0 Description4
       Z38.1 Description5

尝试使用过滤器仅筛选Z38代码

datatmp %>% dplyr::filter(str_detect(Code,'Z38'))

但是会得到以下结果,包括Z38.0和Z38.1。
   Code         Desc
    Z38 Description3
  Z38.0 Description4
  Z38.1 Description5

也尝试使用 datatmp %>% dplyr::filter(grepl('Z38',Code,fixed = TRUE)) 进行筛选并给出样本输出。

注意:我上面提到的例子只有一个值,即筛选条件中的 Z38,实际上这些值是动态的。例如 Z38,Z00 等。

请建议如何找到精确匹配。


3
怎么样:datatmp %>% dplyr :: filter(Code =='Z38') - Wietze314
1
如果你只想要"Z38": datatmp %>% filter(Code =="Z38")如果你想要根据多个值进行筛选: datatmp %>% filter(Code %in% c("Z38","Z00")) - OmaymaS
将筛选条件动态地构建。 - SPS
你的意思是 cond <- "Z38" datatmp %>% filter(Code ==cond) 吗? - OmaymaS
是的,请使用所选的条件和链接查看详细信息[链接](http://stackoverflow.com/questions/41613296/shiny-using-selectizeinput-to-build-dynamic-data-output)。 - SPS
1个回答

3

你的grepl过滤器已经很接近了。将代码更改为:

datatmp %>% dplyr::filter(grepl("^Z38$", Code))

符号^表示字符串的开头(在这种情况下实际上并不必要),符号$表示字符串的结尾,所以Z38.0将无法匹配。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接