Skip to content
Back to formatted view

Raw Message

Message-ID: <CABdHhvGwt-fv_sEd-STazWxTmcWW8b78puWGpGLWEwWKDD2PKg@mail.gmail.com>
Date: 2011-12-03T19:10:04Z
From: Hadley Wickham
Subject: Counting the occurences of a charater within a string
In-Reply-To: <974A7A659261804FA954D102472EA32E03D37A85@NYCEMBP01101.ad.insidemedia.net>

On Thu, Dec 1, 2011 at 10:32 AM, Douglas Esneault
<Douglas.Esneault at mecglobal.com> wrote:
> I am new to R but am experienced SAS user and I was hoping to get some help on counting the occurrences of a character within a string at a row level.
>
> My dataframe, x, ?is structured as below:
>
> Col1
> abc/def
> ghi/jkl/mno
>
> I found this code on the board but it counts all occurrences of "/" in the dataframe.
>
> chr.pos <- which(unlist(strsplit(x,NULL))=='/')
> chr.count <- length(chr.pos)
> chr.count
> [1] 3
>
> I'd like to append a column, say cnt, that has the count of "/" for each row.

Here's an easy way from stringr:

library(stringr)
str_count( c("abc/def", "ghi/jkl/mno"), "/")
# [1] 1 2

Hadley

-- 
Assistant Professor / Dobelman Family Junior Chair
Department of Statistics / Rice University
http://had.co.nz/