[R] "autonumber" for grouping variable

Dimitris Rizopoulos d.rizopoulos at erasmusmc.nl
Mon Feb 23 16:34:15 CET 2009


say 'dat' is your data frame, then one way is the following:

f <- factor(dat$Id, levels = unique(dat$Id))
dat$Number <- unclass(f)
dat


I hope it helps.

Best,
Dimitris


clion wrote:
> Dear R users,
> my dataframe looks like this
> head(dat)
>    Id  sex byear age
> 1 300   m  2003  50
> 2 300   m  2003  36
> 3 402    f  2003  29
> 4 402    f  2003  21
> 5 402    f  2003  64
> 6 150   m  2005  43
> ...
> ...(where Id is just the Identification number of Individual, sex (male or
> female), byear (=birthyear))
> 
> now, I 'd like to add a column, where each Individual gets an automated
> number starting from 1, so that I can number them consecutively
> something which should look like this:
>    Id sex byear age Number
> 1 300   m  2003  50 1
> 2 300   m  2003  36 1
> 3 402    f  2003  29 2
> 4 402    f  2003  21 2
> 5 402    f  2003  64 2
> 6 150   m  2005  43 3
> ...
> ...
> how can I easily do this?
> thanks a lot for any help,
> Birte
> 

-- 
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014




More information about the R-help mailing list