[R] Counting the occurence of each unique "charecter string"

(Ted Harding) Ted.Harding at nessie.mcc.ac.uk
Sun Nov 27 19:27:12 CET 2005


On 27-Nov-05 Marco Visser wrote:
> LS,
>   
>   I would really like to know how to count the frequency/occurrence of 
> chachters inside a dataset. I am working with extreemly large datasets 
> of forest inventory data with a large variety of different species 
> inside it. 
>   Each row inside the dataframe represents one individual tree and the
> simplified dataframe looks something like this:
>   
>   num species dbh   
>   1        sp1           30
>   2        sp1          20
>   3        sp2          30
>   4        sp1          40
>   
>   I need to be able to count the number of individuals per species, so
> I  need a command that will return for each unique species its
> occurence  inside the dataframe; 
>   
>   [sp1]     3
>   [sp2]     1

Does the following help? (Using an artificial example a bit more
complicated than yours). The dataframe "trees" consists of a list
of species names under "Species", and values of a numeric variable
under "X".


  > trees
              Species   X
  1     Larix decidua 203
  2  Pinus sylvestris 303
  3     Larix decidua 202
  4  Pinus sylvestris 301
  5       Picea abies 102
  6       Picea abies 103
  7  Pinus sylvestris 302
  8       Picea abies 101
  9     Larix decidua 201
  10      Picea abies 104
  11      Picea abies 105
  12 Pinus sylvestris 304


  > freqs<-as.data.frame(table(trees$Species))
  > colnames(freqs)<-c("Species","Counts")
  > freqs
             Species Counts
  1    Larix decidua      3
  2      Picea abies      5
  3 Pinus sylvestris      4


  > mean(freqs$Counts)
  [1] 4
  > sd(freqs$Counts)
  [1] 1


Just using table() would give you the same information, but
converting it to a dataframe makes that information more
readily accessible by familiar methods.

Hoping this helps,
Ted.


--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 27-Nov-05                                       Time: 18:27:10
------------------------------ XFMail ------------------------------




More information about the R-help mailing list