[R] adding row ID numbers by group

Henrique Dallazuanna wwwhsd at gmail.com
Tue Mar 2 18:58:46 CET 2010


Try this:

data$ID <-  with(data, ave(group, group, FUN = seq))

On Tue, Mar 2, 2010 at 2:53 PM, Alexander Schwall
<alexander.schwall at gmail.com> wrote:
> 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]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.
>



-- 
Henrique Dallazuanna
Curitiba-Paraná-Brasil
25° 25' 40" S 49° 16' 22" O



More information about the R-help mailing list