[R] Counting cases within present ranges

Rui Barradas ruipbarradas at sapo.pt
Fri May 4 02:00:43 CEST 2012


Hello,

>
> I have a vector wherein the cases are either uniform or mixed-strings (so
> "AAAAAAAAAAA" vs "ABABABABA"). Different parts > of the vector apply to
> different users, so [1:29] is one guy, [30:50] is another, and [51:70] is
> another. There are about
> 100,000 users, and I have an object that lists where each user's range
> begins (ie (1,30,51,etc).
> 
> My question is, how do I count the non-uniform cases in each range,  and
> give the count for each range its own
> value in a new object? 
> 
Try this:

fun <- function(x, g, pattern="AB"){
	segm <- c(g - 1, length(x))[-1]
	sapply(seq_along(g), function(i) sum(grepl(pattern, x[g[i]:segm[i]])))
}

x <- c("AAAAAAAAA", "AAAAAAAAA", "ABABABABA", "AAAAAAAAA", "AAAAAAAAA",
"ABABABABA")
guys <- c(1, 3, 6)

counts <- fun(x, guys)
counts
[1] 0 1 1

Hope this helps,

Rui Barradas


--
View this message in context: http://r.789695.n4.nabble.com/Counting-cases-within-present-ranges-tp4607293p4607427.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list