在R中:矩阵的两种方式匹配
问题描述:
如果我有一个data.frame
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
我想创建一个DEP矩阵作为ROW ID,将ARR作为COL ID,并用相关的匹配NO ...填充该矩阵.
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...
例如
k l m n o
a 6 7 8 9 10 ...etc
每种组合都是唯一的.
DEP和ARR是名称的相同向量.为了清楚起见,我在这里选择了两个不同的示例.
DEP and ARR are the same vector of names. I have chosen two different sample ones here for clarity.
我正在努力使用match对它们进行排序并将其填充到我在下面创建的矩阵模板中:
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!
答
?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