Question

I'm interested in counting the number of different states present in each sequence of my dataset. For sake of simplicity, I'll use a TraMineR example:

  1. starting from this sequence:

    1230 D-D-D-D-A-A-A-A-A-A-A-D

  2. then computing the extract distinct states with the seqdss function obtaining:

    1230 D-A-D

Is there a function to extract the overall number of different states in the sequence only accounting for presence of a state and not its potential repetition along the sequence? In other words, for the case described above I would like to obtain a vector containing for this sequence the value 2 (event A and event D) instead of 3 (1 event A + 2 events D).
Thank you.

Was it helpful?

Solution

You can compute the number of distinct states by first computing the state distribution of each sequence using seqistatd and then summing the number of non-zero elements in each row of the matrix returned by seqistatd. I illustrate below using the biofam data:

library(TraMineR)
data(biofam)
bf.seq <- seqdef(biofam[,10:25])

## longitudinal distributions 
bf.ldist <- seqistatd(bf.seq)
n.states <- apply(bf.ldist,1,function(x) sum(x != 0))

## displaying results
bf.ldist[1:3,]
     0  1 2 3 4 5 6 7
1167 9  0 0 1 0 0 6 0
514  1 10 0 1 0 0 4 0
1013 7  5 0 1 0 0 3 0

n.states[1:3]
1167  514 1013 
   3    4    4 

OTHER TIPS

I might be missing something here, but it looks like you're after unique.

Your expected result is not clear ( maybe because you describe it in English and not in pseudo code). I guess you you are looking for table to count number of states per subject. Here I am using provided with TraMineR package:

library(TraMineR)
data(actcal)
actcal.seq <- seqdef(actcal,13:24)
head(actcal.seq )

     Sequence               
2848 B-B-B-B-B-B-B-B-B-B-B-B
1230 D-D-D-D-A-A-A-A-A-A-A-D
2468 B-B-B-B-B-B-B-B-B-B-B-B
654  C-C-C-C-C-C-C-C-C-B-B-B
6946 A-A-A-A-A-A-A-A-A-A-A-A
1872 D-B-B-B-B-B-B-B-B-B-B-B

Now applying table to the 4th row for example:

tab <- table(unlist(actcal.seq[4,]))
tab[tab>0]
B C 
3 9
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top