简体   繁体   中英

create binary matrix from data.frame

How can I create a binary matrix from a data.frame with two columns where the first column represents eg 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

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

If your data.frame is df , you just have to do

table(df)

另一种可能性:

xtabs(~species+region, data=tab)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM