从data.frame创建二进制矩阵 [英] create binary matrix from data.frame

查看:57
本文介绍了从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!

推荐答案

您正在寻找函数 table ,其文档为

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆