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
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.
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())