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!
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"
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.
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.
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
You are looking for the function table
whose documentation is here
If your data.frame is df
, you just have to do
table(df)
an other possibility :
xtabs(~species+region, data=tab)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With