Question

Hi I need to change the layoyt of my data into a wide matrix

My data look like this

data <- data.frame( 
  species = c("rabbit", "rabbit", "fox", "rabbit", "rabbit", "rabbit"),
  transect = c("EH1", "EH1", "EH1", "EH2", "EH2", "EH2")
  )


species  transect
rabbit    EH1
rabbit    EH1
fox       EH1
rabbit    EH2
rabbit    EH2
rabbit    EH2

I would like to rearrange it into this:

          EH1  EH2
fox        1    0
rabbit     2    3

table give the result like this

species transect freq
rabbit    EH1     2
fox       EH1     1
rabbit    EH2     3
fox       EH2     0

I am no expert and i have been using some time trying to use ddply and reshape, but I have not managed so solve the problem.

Best regards

Was it helpful?

Solution

Very simply using base R functions:

table(data)
#        transect
#species  EH1 EH2
# fox      1   0
# rabbit   2   3

Edit: In response to your edit, you can use:

library(reshape2)
melt(table(data))
#  species transect value
#1     fox      EH1     1
#2  rabbit      EH1     2
#3     fox      EH2     0
#4  rabbit      EH2     3

To get the second output you requested.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top