I have a data set with three columns.
我有一个包含三列的数据集。
X = c("x", "y", "z", "x", "y", "w")
Y = c("a", "b", "c" , "b", "a", "c")
set.seed(3)
Z = sample(10,6)
dat = data.frame(X, Y, Z)
The dat looks like
dat的样子
X Y Z
1 x a 2
2 y b 8
3 z c 4
4 x b 3
5 y a 9
6 w c 6
I want to transform the above data into the format that the rows are X and the columns are Y and the values in the matrix are Z. Essentially I want the following:
我想把上面的数据转换成行为X,列为Y,矩阵值为z的格式。
a b c
x 2 3 0
y 9 8 0
z 0 0 4
w 0 0 6
This is somewhat similar to edge list to adjacency matrix, except the data matrix is not square. Please help. Thanks!
这有点类似于边列表与邻接矩阵,除了数据矩阵不是方阵。请帮助。谢谢!
1 个解决方案
#1
4
Try
试一试
library(reshape2)
acast(dat, X~Y, value.var='Z', fill=0)
To get the rows in order as the expected result
使行按照预期结果排列
acast(dat, factor(X, levels=unique(X))~Y, value.var='Z', fill=0)
Or as @thelatemail commented
或@thelatemail评论
xtabs(Z~X+Y, data= dat)[unique(dat$X),]
Or a modified version if both columns are not in order
或者,如果两个列都不符合要求,则修改版本。
with(dat, xtabs(Z ~ X + Y)[unique(X), unique(Y)])
#1
4
Try
试一试
library(reshape2)
acast(dat, X~Y, value.var='Z', fill=0)
To get the rows in order as the expected result
使行按照预期结果排列
acast(dat, factor(X, levels=unique(X))~Y, value.var='Z', fill=0)
Or as @thelatemail commented
或@thelatemail评论
xtabs(Z~X+Y, data= dat)[unique(dat$X),]
Or a modified version if both columns are not in order
或者,如果两个列都不符合要求,则修改版本。
with(dat, xtabs(Z ~ X + Y)[unique(X), unique(Y)])