grep using a character vector with multiple patterns

前端 未结 10 2319
猫巷女王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:22

    Using the sapply

     patterns <- c("A1", "A9", "A6")
             df <- data.frame(name=c("A","Ale","Al","lex","x"),Letters=c("A1","A2","A9","A1","A9"))
    
    
    
       name Letters
    1    A      A1
    2  Ale      A2
    3   Al      A9
    4  lex      A1
    5    x      A9
    
    
     df[unlist(sapply(patterns, grep, df$Letters, USE.NAMES = F)), ]
      name Letters
    1    A      A1
    4  lex      A1
    3   Al      A9
    5    x      A9
    

提交回复
热议问题