[R] matching character substrings

John Fox jfox at mcmaster.ca
Fri Aug 24 21:16:24 CEST 2001


Dear David,

At 12:23 PM 24/08/2001 -0400, David White wrote:

>Hello,
>
>Is there a function for searching a string for a given character? For
>example, I have
>transcriptions like
>
>tsibi
>tSibi
>tibi
>kibi
>
>I want to search the character object for the presence of 's' or 'S' or
>'k'.
>
>I thought perhaps pmatch(c("k", "S", "s"), x) would work for me, but it
>wants to compare from the start of the string and returns NA for "S" and
>"s" because they are not at the head of the string.

The function grep or regexpr should do what you want; for example:

 > vec <- c('tsibi', 'tSibi', 'tibi', 'kibi')

 > grep('[sSk]', vec)
[1] 1 2 4

 > regexpr('[sSk]', vec)
[1]  2  2 -1  1
attr(,"match.length")
[1]  1  1 -1  1

 >

See the help files for details.

I hope that this helps,
  John



-----------------------------------------------------
John Fox
Department of Sociology
McMaster University
Hamilton, Ontario, Canada L8S 4M4
email: jfox at mcmaster.ca
phone: 905-525-9140x23604
web: www.socsci.mcmaster.ca/jfox
-----------------------------------------------------

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list