[R] presence/absence matrix

(Ted Harding) ted.harding at nessie.mcc.ac.uk
Fri Jul 20 17:14:18 CEST 2007


On 20-Jul-07 14:16:39, rocchini at unisi.it wrote:
> I have a table such that:
> 
> sample #   species
> 1    a
> 1    b
> 2    a   
> 2    c
> 3    b     
> 
> and i would like to build a matrix with species names (i.e. a b and c) 
> as field names and samples (i.e. 1,2 and 3) as row names
> and 1/0 as inner values
> such as:
>     a   b   c
> 1   1   1   0
> 2   1   0   1
> 3   0   1   0
> 
> I am currently using Rcmdr package for managing datasets but need a 
> function about.... I tried to use stack function but only with worst
> results

The following generates the sort of thing you show above:

## Identities of possible species and samples
  Species<-c("a","b","c","d")
  Samples<-c(1,2,3,4,5,6)

## Generate a set of samples and corresponding species:
  species<-sample(Species,20,replace=TRUE)
  samples=sample(Samples,20,replace=TRUE)
## Have a look:
 cbind(samples,species)
      samples species
 [1,] "5"     "c"    
 [2,] "2"     "c"    
 [3,] "4"     "a"    
 [4,] "5"     "b"    
 [5,] "5"     "d"    
 [6,] "1"     "d"    
 [7,] "2"     "b"    
 [8,] "2"     "b"    
 [9,] "3"     "b"    
[10,] "2"     "d"    
[11,] "4"     "d"    
[12,] "1"     "b"    
[13,] "3"     "b"    
[14,] "2"     "c"    
[15,] "2"     "d"    
[16,] "6"     "b"    
[17,] "5"     "a"    
[18,] "4"     "a"    
[19,] "2"     "b"    
[20,] "5"     "a"    

## Now generate a table:
  T<-table(samples,species)
  T
          species
  samples a b c d
        1 0 1 0 1
        2 0 3 2 2
        3 0 2 0 0
        4 2 0 0 1
        5 2 1 1 1
        6 0 1 0 0

Now this is a "table" structure, and also gives counts of
occurrences and not merely presence/absence. So we need to
get these out as a matrix.

  U<-as.matrix(T)
  U
          species
  samples a b c d
        1 0 1 0 1
        2 0 3 2 2
        3 0 2 0 0
        4 2 0 0 1
        5 2 1 1 1
        6 0 1 0 0

  U<-1*(U>0)
  U
          species
  samples a b c d
        1 0 1 0 1
        2 0 1 1 1
        3 0 1 0 0
        4 1 0 0 1
        5 1 1 1 1
        6 0 1 0 0

Is that what you want?
Best wishes,
Ted.

--------------------------------------------------------------------
E-Mail: (Ted Harding) <ted.harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 20-Jul-07                                       Time: 16:14:14
------------------------------ XFMail ------------------------------



More information about the R-help mailing list