Search code examples
rdataframevegan

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...


Solution

  • 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