Monday, July 23, 2007

Run Length

A small function to get runlength from a vector



runlength=function(x){
run=1
k=1
for( i in 2: length(x)){
if(x[i]==x[i-1]) run[k]=run[k]+1
else{
k=k+1
run=c(run,1)
}
}

return(run)
}

2 comments:

JLMC said...

I like it when people post such snippets. But there is a function in the base library, rle(), which will do the same and is faster.

surajit.ray said...

Thanks JLMC