[R] adding row ID numbers by group

Felipe Carrillo mazatlanmexico at yahoo.com
Tue Mar 2 19:08:59 CET 2010


Like this?

group<- c(1,1,1,1,2,2,2,2,2,3,3,3,3,3,3)
var2<- c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
data<-data.frame(group, var2)
data
ddply(data,"group",transform,ID=1:length(group))
 
Felipe D. Carrillo
Supervisory Fishery Biologist
Department of the Interior
US Fish & Wildlife Service
California, USA



----- Original Message ----
> From: Alexander Schwall <alexander.schwall at gmail.com>
> To: r-help at r-project.org
> Sent: Tue, March 2, 2010 9:53:19 AM
> Subject: [R] adding row ID numbers by group
> 
> Hello R community,

I am hoping for some help with the following 
> problem.

I have a data frame containing various groups. These groups are 
> identified
by a grouping variable. I would like to add a sequential ID number 
> to each
group to later sort these individuals within each group by this ID 
> number.

Here is what the final result should look like:

ID  
> group var2
1      1    1
2      
> 1    2
3      1    3
4    
>   1    4
1      2    5
2  
>     2    6
3      2    
> 7
4      2    8
5      2  
>   9
1      3  10
2      3  
> 11
3      3  12
4      3  
> 13
5      3  14


I have created the following 
> code to loop through this and compare a given
row with the following row for 
> the grouping variable. If a given row would
be different from the then 
> following row, the ID number would be reset and I
would start counting up 
> again. The problem that I am encountering that at
the bottom of the data 
> frame the if statement runs out of a condition
against which to compare the 
> last row.

Here is what I did:

group<- 
> c(1,1,1,1,2,2,2,2,2,3,3,3,3,3,3)
var2<- 
> c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)

data<-data.frame(group, 
> var2)
data

#IDN is the desired ID number by group
IDN 
> <-numeric(length(test$var2))
IDN


for (i in 
> 1:(length(data$group))) {
      if(data[i,1] < 
> (length(data$group))){
          if(data[i,1] == 
> data[i+1,1]){
              IDN[i]<- 
> sum(IDN[i-1],1)}
          else{
    
>           IDN[i]<- -55} #for now an arbitrary 
> value
      }
      if(data[i,1] == 
> (length(data$group))) {
          IDN[i] <- 99 
> #for now an arbitrary value
      }
  
> }

IDN



Is there maybe an easier way to do this? Any 
> thoughts would be very
appreciated since I am running out of 
> ideas.

Thanks
Alexander

    [[alternative HTML 
> version deleted]]

______________________________________________
> ymailto="mailto:R-help at r-project.org" 
> href="mailto:R-help at r-project.org">R-help at r-project.org mailing list
> href="https://stat.ethz.ch/mailman/listinfo/r-help" target=_blank 
> >https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting 
> guide http://www.R-project.org/posting-guide.html
and provide commented, 
> minimal, self-contained, reproducible code.






More information about the R-help mailing list