简体   繁体   中英

make new columns based on other columns in r

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

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

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