4

I'm stuck with something that usually is pretty easily in other programming languages.

I want to test whether a string is inside another one in R. For example I tried:

match("Diagnosi Prenatale,Esercizio Fisico", "Diagnosi Prenatale")
pmatch("Diagnosi Prenatale,Esercizio Fisico", "Diagnosi Prenatale")
grep("Diagnosi Prenatale,Esercizio Fisico", "Diagnosi Prenatale")

And none worked. To make it work I should fist split the first string with strsplit and extract the first element.

NOTE: I'd like to do this on a vector of strings to receive a yes/no vector, so in the function I wrote should go a vector not a single string. But of course if the single string doesn't work, image a full vector of them...

Any ideas?

1
  • 2
    Some quick notes: (1) you wouldn't use match or pmatch for this task - these are for matching in a list. (2) you're using grep incorrectly - the pattern is the first argument and the text is the second. Commented May 30, 2014 at 14:50

1 Answer 1

4

Try grepl

grepl("Diagnosi Prenatale","Diagnosi Prenatale,Esercizio Fisico" )
[1] TRUE

You can also do this with character vectors, for example:

x <- c("Diagnosi Prenatale,Esercizio Fisico", "Diagnosi Prenatale")
grepl("Diagnosi Prenatale",x)
#[1] TRUE TRUE
Sign up to request clarification or add additional context in comments.

1 Comment

Good answer. I would note that the OP used grep incorrectly which is why his code didn't work. I'm often throw off by the fact that pattern is the first argument.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.