1
votes

If I have a data.frame

df <- data.frame(DEP=letters[1:5], ARR=letters[11:15], NO=1:5+5)

   DEP ARR  NO
1   a   k   6
2   b   l   7
3   c   m   8
4   d   n   9
5   e   o  10

I want to create a matrix of DEP as ROW ID, and ARR as COL ID, and fill in the matrix with the relevant matching NO...

e.g.

  k l m n o
a 6 7 8 9 10 ...etc

Each combination is unique.

DEP and ARR are the same vector of names. I have chosen two different sample ones here for clarity.

I am struggling to use match to sort them and fill them into the matrix template I created below:

mat <- matrix(0,nrow(df),nrow(df)); colnames(mat) <- df$ARR; rownames(mat) <- df$DEP;

  k l m n o
a 0 0 0 0 0
b 0 0 0 0 0
c 0 0 0 0 0
d 0 0 0 0 0
e 0 0 0 0 0

Is there an efficient way of doing this? Many thanks for all advice!

2

2 Answers

5
votes

?xtabs:

xtabs(NO ~ ., data=df)
#   ARR
#DEP  k  l  m  n  o
#  a  6  0  0  0  0
#  b  0  7  0  0  0
#  c  0  0  8  0  0
#  d  0  0  0  9  0
#  e  0  0  0  0 10
3
votes

If I understood your question correctly, you could use a sparse matrix definition:

library(Matrix)
mat <- spMatrix(length(df$DEP), length(df$ARR), 
                seq(df$DEP), seq(df$ARR), as.numeric(as.character(df$NO)))
rownames(mat) <- df$DEP
colnames(mat) <- df$ARR
#> as.matrix(mat)
#  k l m n  o
#a 6 0 0 0  0
#b 0 7 0 0  0
#c 0 0 8 0  0
#d 0 0 0 9  0
#e 0 0 0 0 10