Rajarshi Bhadra
Rajarshi Bhadra

Reputation: 1944

Generate pairwise movement data from sequence

I have a sequence which looks like this

  SEQENCE
1       A
2       B
3       B
4       C
5       A

Now from this sequence, I want to get the matrix like this where i the row and jth column element denotes how many times movement occurred from ith row node to jth column node

  A B C
A 0 1 0
B 0 1 1
C 1 0 0

How Can I get this in R

Upvotes: 0

Views: 36

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269371

1) Use table like this:

s <- DF[, 1]
table(tail(s, -1), head(s, -1))

giving:

    A B C
  A 0 0 1
  B 1 1 0
  C 0 1 0

2) or like this. Since embed does not work with factors we convert the factor to character,

s <- as.character(DF[, 1])
do.call(table, data.frame(embed(s, 2)))

giving:

   X2
X1  A B C
  A 0 0 1
  B 1 1 0
  C 0 1 0

3) xtabs also works:

s <- as.character(DF[, 1])
xtabs(data = data.frame(embed(s, 2)))

giving:

   X2
X1  A B C
  A 0 0 1
  B 1 1 0
  C 0 1 0

Note: The input DF in reproducible form is:

Lines <- "  SEQENCE
1       A
2       B
3       B
4       C
5       A"
DF <- read.table(text = Lines, header = TRUE)

Upvotes: 1

Related Questions