[R] Counting value changes

peter dalgaard pdalgd at gmail.com
Sun Feb 19 09:09:36 CET 2012


On Feb 19, 2012, at 04:25 , jim holtman wrote:

> For completeness, if you want to count all possible four transitions:
> 
>> x <- c(0,1,0,1,0,0,0,1,1,1,0,0,0,1)
>> # lets keep count of the 4 different transitions that can happen
>> indx <- cbind(head(x, -1), tail(x, -1)) %*% c(2, 1)
>> table(indx) # 0=0-0, 1=0-1, 2=1-0, 3=1-1
> indx
> 0 1 2 3
> 4 4 3 2
>> 

Um, why not just this?

> table(from=head(x, -1), to=tail(x, -1))
    to
from 0 1
   0 4 4
   1 3 2



-- 
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list