1

I'm looking for a simple function that will number cases chronologically by another variable in R.

For example:
ID  Age Case
1   30  1
2   30  2
3   30  3
4   31  1
5   31  2
6   32  1
7   32  2
Microsim
  • 75
  • 1
  • 4

2 Answers2

0

Here's one way:

df <- data.frame(ID=c(1L,2L,3L,4L,5L,6L,7L),Age=c(30L,30L,30L,31L,31L,32L,32L));
df$Case <- ave(df$ID,df$Age,FUN=order);
df;
##   ID Age Case
## 1  1  30    1
## 2  2  30    2
## 3  3  30    3
## 4  4  31    1
## 5  5  31    2
## 6  6  32    1
## 7  7  32    2

Using order() as the group function ensures that the Case values will be ordered according to the ID column, even if it is not sorted.

bgoldst
  • 34,190
  • 6
  • 38
  • 64
0

Here is a compact option with splitstackshape

library(splitstackshape)
getanID(df1, "Age")[]

Or using dplyr

library(dplyr)
df1 %>%
     group_by(Age) %>%
     mutate(Case = row_number())
akrun
  • 874,273
  • 37
  • 540
  • 662