从data.frame创建二进制矩阵 [英] create binary matrix from data.frame
问题描述
如何从具有两列的data.frame中创建二进制矩阵,其中第一列表示例如物种和其他地区?data.frame的格式如下所示
How can I create a binary matrix from a data.frame with two columns where the first column represents e.g. species and the other their region? The data.frame is in tall format as seen below
species region
species1 1
species1 2
species1 3
species2 2
species2 4
species2 5
species2 6
species3 1
species3 2
species4 5
species5 3
species5 4
并且矩阵会将所有唯一的物种作为行,并将所有唯一的区域作为列.对于存在的物种,矩阵将填充为 1s
,对于不存在的物种将填充为 0s
,如下所示
And the matrix would have all unique species as rows and all unique regions as columns. The matrix would be filled with 1s
for species present and 0s
for species absent, as below
1 2 3 4 5 6
species1 1 1 1 0 0 0
species2 0 1 0 1 1 1
species3 1 1 0 0 0 0
species4 0 0 0 0 1 0
species5 0 0 1 1 0 0
非常感谢任何指针,谢谢!
Any pointers would be very much appreciated, thanks!
推荐答案
You are looking for the function table
whose documentation is here
如果您的data.frame是 df
,则只需要做
If your data.frame is df
, you just have to do
table(df)
这篇关于从data.frame创建二进制矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!