# [R] Simple Coding problem ?

Jonathan Baron baron at cattell.psych.upenn.edu
Sun Apr 21 18:07:01 CEST 2002

```On 04/21/02 10:33, Calvin L. Williams, Ph.D. wrote:
>R-users,
>
>This may be a simple problem, but I don't have an intuition of
>how simple it could be. Suppose I have a sequence of numbers
>corresponding to a series of diagnoses on the same patient
>over a sequence of time. The diagnoses are coded 1,2,3,4,5, but
>could come in a sequence like 1,3,2,5,3,5,...etc. Is there a simple
>way to count the number of times a 1 diagnosis is followed by a 2, or
>a 3, ... A 2 by a 1, or 3,....etc. It's almost like a mover-stayer problem.
>I think.

Suppose you have these in a vector v1.  How about something like

w1 <- length(v1)
table(v1[-w1],v1[2:w1])

If each subject is a row in a matrix m1, then you could do this
something like (where w1 is now the number of columns)

apply(m1,1,function(x) table(x[-w1],x[2:w1]))

I haven't tested this, and I might have it slightly wrong, or not
optimal.

I'm sure there are better ways, but I'm sure this general idea
will work.

--
Jonathan Baron, Professor of Psychology, University of Pennsylvania