[R] pattern search

Julien Barnier julien at no-log.org
Wed Apr 4 17:49:42 CEST 2007


Hi,

> I'm looking for an easy possibility for pattern search. I have got a
> string and a special pattern. I would like to know if the pattern
> appears in the string, if yes where does it appear (position) and the
> number of appearance.  
> 
> Example:
> 
> Text = c("If the sun shines, no clouds should be seen in the sky!")
> SearchPattern = c("the")
> NumberOfAppearance = 0
> NumberOfLetters = 0
> 
> --> NumberOfAppearance should be 2 in the end

I think you are looking for the gregexpr function.

R> Text = c("If the sun shines, no clouds should be seen in the sky!")
R> gregexpr("the", Text)
[[1]]
[1]  4 48
attr(,"match.length")
[1] 3 3

> How can I get the string length (=number of letters stored in Text)?

Maybe the nchar funtion ?

R> nchar(Text)
[1] 55

HTH,

-- 
Julien



More information about the R-help mailing list