[R] adding a frequency variable to a data frame

Michael Friendly friendly at yorku.ca
Fri Apr 11 22:40:47 CEST 2014


I'm sure this is pretty simple, but it's Friday afternoon, and I just 
don't see it...

In a data frame with a categorical/character factor, I want to add another
column giving, for each observation, the frequency of that factor level.

An example, where the variable of interest is family:

 > data("Donner", package="vcdExtra")
 > str(Donner)
'data.frame':   90 obs. of  5 variables:
  $ family  : Factor w/ 10 levels "Breen","Donner",..: 9 1 1 1 1 1 1 1 1 
1 ...
  $ age     : int  23 13 1 5 14 40 51 9 3 8 ...
  $ sex     : Factor w/ 2 levels "Female","Male": 2 2 1 2 2 1 2 2 2 2 ...
  $ survived: int  0 1 1 1 1 1 1 1 1 1 ...
  $ death   : POSIXct, format: "1846-12-29" NA ...
 > table(Donner$family)

     Breen    Donner      Eddy  FosdWolf    Graves  Keseberg McCutchen 
MurFosPik
         9        14         4         4        10 4         3        12
     Other      Reed
        23         7
 >

Here, I want to create a new variable, family.size,   where all the 
Breens have 9,
the Donners, 14,  and so on...

-- 
Michael Friendly     Email: friendly AT yorku DOT ca
Professor, Psychology Dept. & Chair, Quantitative Methods
York University      Voice: 416 736-2100 x66249 Fax: 416 736-5814
4700 Keele Street    Web:   http://www.datavis.ca
Toronto, ONT  M3J 1P3 CANADA




More information about the R-help mailing list