dplyr过滤器,如果一列以列表中的字符串之一开头

时间:2018-10-17 05:47:28

标签: r filter dplyr

我们的目标:使用R dplyr,如果match_column字段中的数据以code_list <-c(“ 123”,“ 234”,“ 456”))中的代码之一开头,则对该行进行过滤。

以下内容适用于静态字符串(即,它返回数据集:: match_column中以静态字符串“ 123”开头的所有行。)

dataset1 <-filter(dataset, str_detect(match_column,"^123"))

经过无数次尝试,我们无法弄清用code_list替换“ ^ 123”的语法。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

我们可以使用paste collapse字符串来进行filter来过滤数据集列(“ match_column”)中具有“ code_list”中任一元素的行'

library(tidyverse)
pat <-  paste0("^(", paste(code_list, collapse = "|"), ")")
dataset %>%
     filter(str_detect(match_column, pat))

如果仅使用“ code_list”中的元素之一

dataset %>%
     filter(str_detect(match_column, paste0("^", code_list[1])))