[R] how to count occurrences of string?

Stefan Th. Gries stgries at gmail.com
Mon Sep 21 18:24:07 CEST 2009


This should do what you want:

set.seed(1)
# cerating a vector with comments, in which d's will be counted
comments<-character(25)
for (i in 1:25) {
   comments[i] <- paste(sample(letters[1:10], 10, replace=T), collapse="")
}

# creating a vector to cross -tabulate
age <-sample(c("old", "young"), 25, replace=T)

# find d's in comments, determine their frequencies, and crosstab
table(sapply(gregexpr("d", comments), length), age)

HTH,
STG




More information about the R-help mailing list