Yuan.guo
Yuan.guo

Reputation: 41

How to convert a data.frame to a matrix?

I have a data frame like this: three columns, species, the compounds emitted by the species, and 1 in status means the compound present in the species. And in this format, there is no 0, which will indicate "absent".

enter image description here

Now, I want convert the data frame to a matrix like this: first column with species, the rest of the columns with compounds, and use 1 and 0 indicate "present" and "absent", respectively.

enter image description here

Is there a R code can do this? As you can see, there are so many rows in the original data frame. Thank you in advance!

Upvotes: 1

Views: 70

Answers (1)

akrun
akrun

Reputation: 887158

We can use dcast

library(reshape2)
dcast(data, species ~compounda, value.var = 'status', fill = 0)

If we need a matrix use change dcast to acast

Upvotes: 2

Related Questions