Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 450
Bakaburg Avatar asked Oct 16 '25 23:10

Bakaburg


1 Answers

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
like image 199
talat Avatar answered Oct 19 '25 11:10

talat