Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 527
jO. Avatar asked Mar 06 '14 10:03

jO.


People also ask

How to quickly convert a data frame to a numeric matrix?

We can use the as.matrix () function to quickly convert this data frame to a numeric matrix: #convert data frame to matrix mat <- as.matrix(df) #view matrix mat points assists rebounds [1,] 99 33 30 [2,] 90 28 28 [3,] 86 31 24 [4,] 88 39 24 [5,] 95 34 28 #view class of mat class (mat) [1] "matrix" "array"

How to create Matrix and data frame using lists in R?

In this article, we’ll learn to create matrix and data frame using lists. Matrices are created using matrix () function in R programming. Another function that will be used is unlist () function to convert the lists into a vector. The vector created contains atomic components of the given list. recursive: represents logical value.

How to return a matrix from a data frame in Python?

By using the class () function, we confirm that the new object is indeed a matrix. Description: Return the matrix obtained by converting all the variables in a data frame to numeric mode and then binding them together as the columns of a matrix. Factors and ordered factors are replaced by their internal codes.

How to create a Dataframe using lists in Python?

In the same way, dataframe can be created using lists by using unlist () function and data.frame () function. The dataframe is : Number Letters Month 1 1 a January 2 2 b February 3 3 c March


2 Answers

You are looking for the function table whose documentation is here

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

table(df)
like image 162
Pop Avatar answered Sep 20 '22 14:09

Pop


an other possibility :

xtabs(~species+region, data=tab)
like image 32
droopy Avatar answered Sep 17 '22 14:09

droopy