Counting the occurences of a charater within a string
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/