-1

to check if a string contains a given element we can do

strings <- c("4|x|4", "4x4", "1|x|1")
element <- "4"
grepl(element, strings)
#[1]  TRUE  TRUE FALSE

but if the element is a | this no longer works.

 grepl("|", strings)
 #[1] TRUE TRUE TRUE

How can we return TRUE,FALSE,TRUE?

SOFe
  • 7,867
  • 4
  • 33
  • 61
user1320502
  • 2,510
  • 5
  • 28
  • 46

1 Answers1

1

The | is a metacharacter meaning OR or either. To evaluate the literal string value, either escape (\\) or place it inside brackets ([]) or use the fixed = TRUE argument

grepl("|", strings, fixed = TRUE)
#[1]  TRUE FALSE  TRUE
akrun
  • 874,273
  • 37
  • 540
  • 662