3

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

Community
  • 1
  • 1
Monal
  • 127
  • 1
  • 6
  • `library(reshape2);acast(df1, sample.id~speciesname, value.var='count', fill=0)` can be also used – akrun Mar 29 '15 at 10:39

1 Answers1

5

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
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245