[R] character occurence within a string

Prof Brian Ripley ripley at stats.ox.ac.uk
Mon Feb 21 13:14:28 CET 2005


Here are two ways for one string, both easily vectorized:

1) sum(charToRaw(x) == charToRaw("|"))

2) sum(strsplit(x, "")[[1]] == "|")

In R-devel the first looks for bytes and the second for characters, and in 
UTF-8 locale there is a difference.

On Mon, 21 Feb 2005, Marc Mamin wrote:

> Hello,
>
> I'm looking for a function that counts the occurences of a given 
> character within a string.
>
> f('|','ab|c|d') => 2
>
>
> More precisely, I need to complete a vector of strings to ensure that 
> all elements have the same count of a "separator":
>
> 	a|b|c
> 	a
> 	|a|b|c|d
>
> 	=>
>
> 	a|b|c||
> 	a||||
> 	|a|b|c|d
>
> I guess that scan makes use of an internal function that would do the job...

No, it works on an internal buffer.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list