Reputation: 183
I have a boolean vector derived from a time series. It basically looks like this: c(true, false, true, true, false, false, false, true, true...).
I want to count the periods in which the vector is true. Example: for a vector like this: c(true, true, false, true) it would be 2 (1 long true period in the beginning, 1 short in the end).
the vector can contain NAs in the beginning.
I thought of something like:
aaa <- c(NA,F,T,T,T,F)
for(j in 1:(length(aaa)-1)){
if(aaa[j]!=aaa[j+1]){
# add a counter that returns [1]
}
}
=================================================
edit: This works fine for me:
data.frame("#"=unlist(rle(aaa)[1]),"length"=unlist(rle(aaa)[2]))
Upvotes: 0
Views: 126
Reputation: 7941
How about this:
aaa[is.na(aaa)] <- FALSE
sum(rle(aaa)$values)
Convert NA
s to FALSE
, and the see how many TRUE
values there are in the run length encoding (TRUE
is stored as 1, FALSE
as zero).
Upvotes: 1