?lag
?xtabs
songseq <- read.table(textConnection("Nr Songtype
1 S1
2 S2
3 S3
4 S1
5 S1
6 S2
7 S4"), header=TRUE, stringsAsFactors=FALSE)
songseq$precsong <-c(NA,lag(songseq$Songtype)[1:6])
# need to drop last entry
xtabs( ~ precsong + Songtype, data=songseq)
Songtype
precsong S1 S2 S3 S4
S1 1 2 0 0
S2 0 0 1 1
S3 1 0 0 0
#may want to set extra levels if S4 song type does not have a subsequent
--
David Winsemius, MD
Heritage Laboratories
West Hartford, CT
On Mar 6, 2009, at 3:14 PM, miweiss1 at freenet.de wrote:
> Hello,
> The example shows a sequence of songtypes a bird has sang.
> The entire list contains several thousand songs which the bird has
> produced consecutively.
> Is there any convenient way in R to produce a contingency table
> which shows how often a special song type was sang after a special
> other songtype? Or within a determined frame of e.g. 10
> consecutively produced songs?
>
> Example:
>
> Nr Songtype
> 1 S1
> 2 S2
> 3 S3
> 4 S1
> 5 S1
> 6 S2
> 7 S4
>
> Contingency table:
>
> S1 S2 S3 S4 subsequent songs
> S1 1 2 0 0
> S2 0 0 1 1
> S3 1 0 0 0
> S4 0 0 0 0
> Preceding
> Songs
>
>
> Greetings
> Michael