Bakaburg
Bakaburg

Reputation: 3311

match part of string in R

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?

Upvotes: 4

Views: 6541

Answers (1)

talat
talat

Reputation: 70256

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

Upvotes: 4

Related Questions