简体   繁体   中英

data.frame conversion in r

I have a df with a bunch of columns. Each row represents a species seen for each sampling trip. I want to convert this to a matrix or dataframe where each column is a species and each row is a sampling trip. I want to convert it for analysis using vegan functions. I basically want the opposite of this melting data.frame in R

Original format

data.frame(speciesname=c("a","b","c","a"),sample.id=c(1,1,2,3),count=c(10,1,5,2))

speciesname sample.id count
1           a         1    10
2           b         1     1
3           c         2     5
4           a         3     2

I want to convert it to look like this:

   a b c
1 10 1 0
2  0 0 5
3  2 0 0

I am trying not to make some hideous double for loop with if statements but if that is what I have to do...

Using xtabs()

xtabs(count ~ sample.id + speciesname, df)
#          speciesname
# sample.id  a  b  c
#         1 10  1  0
#         2  0  0  5
#         3  2  0  0

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