grep using a character vector with multiple patterns

前端 未结 10 2329
猫巷女王i
猫巷女王i 2020-11-22 04:29

I am trying to use grep to test whether a vector of strings are present in an another vector or not, and to output the values that are present (the matching pat

10条回答
  •  情话喂你
    2020-11-22 05:10

    Good answers, however don't forget about filter() from dplyr:

    patterns <- c("A1", "A9", "A6")
    >your_df
      FirstName Letter
    1      Alex     A1
    2      Alex     A6
    3      Alex     A7
    4       Bob     A1
    5     Chris     A9
    6     Chris     A6
    
    result <- filter(your_df, grepl(paste(patterns, collapse="|"), Letter))
    
    >result
      FirstName Letter
    1      Alex     A1
    2      Alex     A6
    3       Bob     A1
    4     Chris     A9
    5     Chris     A6
    

提交回复
热议问题