Kitumijasi
Kitumijasi

Reputation: 411

Numerate by Group in R

I have a data.frame (DF) like the following:

      [ID]   [Value]  
[1]   ID_1    5
[2]   ID_2    6
[3]   ID_2    9
[4]   ID_3    1
[5]   ID_3    445
[6]   ID_3    10
          etc.

What i need is to numarate the observations (backwards) by the ID column so that the solution looks like:

       [ID]    [Value]  [Observation] 
  [1]  ID_1     5       1
  [2]  ID_2     6       2
  [3]  ID_2     9       1
  [4]  ID_3     1       3
  [5]  ID_3     445     2
  [6]  ID_3     10      1
            etc.

All that in a flexible way because the number of observations can differ. It would be great if that would be possible with a base R solution. I found a solution which does that counting up from 1:

DF$Observation<-do.call(c, lapply(unique(DF$ID), function(enum){
  seq(sum(DF$ID==enum))
}))

Well if it Helps in any way originaly the data ist stored in a list with every "ID_" as a num vector. Perhaps it is easier to start here and wirte code which saves the values in "backwards" order.

myList <- list(ID_1 = 5, ID_2=c(6,9),ID_3=c(1,445,10))

Upvotes: 2

Views: 221

Answers (1)

akrun
akrun

Reputation: 887891

We can try with ave

 DF$Observation <- with(DF, ave(Value, ID, FUN= function(x) rev(seq_along(x))))
 DF$Observation
 #[1] 1 2 1 3 2 1

data

DF <- data.frame(ID=c('ID_1', 'ID_2', 'ID_2', 'ID_3', 'ID_3', 'ID_3'),
     Value=c(5,6,9,1, 445, 10), stringsAsFactors=FALSE)

Upvotes: 3

Related Questions