3

Say I have a character vector a like the following:

a <- c(paste("P",1:5,"AA+1","a",8:12), paste("P",6:8,"BA-2","a",25:27), paste("P",9:16,"ZZ*3","a",25:32), paste("P",17:20,"CD/4","a",4:7), paste("P",21:24,"XY&9","a",112:113))
> a
 [1] "P 1 AA+1 a 8"    "P 2 AA+1 a 9"    "P 3 AA+1 a 10"   "P 4 AA+1 a 11"  
 [5] "P 5 AA+1 a 12"   "P 6 BA-2 a 25"   "P 7 BA-2 a 26"   "P 8 BA-2 a 27"  
 [9] "P 9 ZZ*3 a 25"   "P 10 ZZ*3 a 26"  "P 11 ZZ*3 a 27"  "P 12 ZZ*3 a 28" 
[13] "P 13 ZZ*3 a 29"  "P 14 ZZ*3 a 30"  "P 15 ZZ*3 a 31"  "P 16 ZZ*3 a 32" 
[17] "P 17 CD/4 a 4"   "P 18 CD/4 a 5"   "P 19 CD/4 a 6"   "P 20 CD/4 a 7"  
[21] "P 21 XY&9 a 112" "P 22 XY&9 a 113" "P 23 XY&9 a 112" "P 24 XY&9 a 113"

And I need to detect the elements inside 3 groups stored in another character vector gs, via grep:

gs <- c("AA+1","ZZ*3","XY&9")

The problem, as you see, is that these groups contain special characters.

I know I could do:

grep("AA\\+1", a, val=TRUE)

But what about when what I want to grep is inside a vector? I cannot do:

grep(gs[1], a, val=TRUE)
character(0)
oguz ismail
  • 1
  • 16
  • 47
  • 69
DaniCee
  • 2,397
  • 6
  • 36
  • 59

1 Answers1

1

Just to provide some context and settle the case:

  • The option fixed=TRUE defines that the pattern is a string to be matched as is (literally) rather than a regular expression. The option also overrides all conflicting arguments (doc).

  • fixed=TRUE does not mean it works like grep -w in bash, which finds a string that is a separate word (enclosed by space/boundries). The string can still be a substring of a word in the source text/character vector.

wp78de
  • 18,207
  • 7
  • 43
  • 71