I have a data.table:
example <- data.table(year = c(2016, 2017, 2018, 2016, 2017, 2020),
ID = c("A","A","A", "B", "B","B"))
and I need an order variable for the years. The highest year having the smallest rank, for every id separately. The result would then be:
exmampleResult <- data.table(year = c(2016, 2017, 2018, 2016, 2017, 2020),
ID = c("A","A","A", "B", "B","B"),
yearRank = c(3, 2, 1, 5, 4, 1))
How can this be done in data.table?
I tried splitting the data table in a list of list:
exampleList <- lapply(split(example,example$ID), function(x) as.list(x))
and then calculating the order using another apply. However that seems too complicated. Is there a simpler way?