1

I have a dataframe with species name and Habitat_id. I want to make new columns based on Habitat_id and assign species according to their Habitat_id. For example, my dataframe looks like below:

Species_Name Habitat_id  
abc cde         85  
acc bcc         26  
acd dcc         138  
acp acp         35  
acp acp         37  
acp acp         38  
bpp cpp         26  
qpp qlp         26  
qpp qlp         22  
qpp qlp         24

I want the new dataframe will be look like:

Species_Name 22 24 26 35 37 38 85 138  
abc cde       0  0  0  0  0  0  1  0  
acc bcc       0  0  1  0  0  0  0  0  
acd dcc       0  0  0  0  0  0  0  1  
acp acp       0  0  0  1  1  1  0  0  
bpp cpp       0  0  1  0  0  0  0  0  
qpp qlp       1  1  1  0  0  0  0  0
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
Tiny_hopper
  • 380
  • 1
  • 4
  • 15

1 Answers1

2

We can do this with table

df2 <- as.data.frame.matrix(table(df1))
df2 <- cbind(Species_Name = row.names(df2), df2)
row.names(df2) <- NULL
akrun
  • 874,273
  • 37
  • 540
  • 662