I have a dataframe like this:
ID <- c("AB1","AB1","CD2","AB3","KK4","AB3","AB3","AB1","AB1","CD2")
year <- c(2005,2008,2005,2010,2007,2009,2009,2007,2000,2010)
df <- data.frame(ID, year)
df
ID year
1 AB1 2005
2 AB1 2008
3 CD2 2005
4 AB3 2010
5 KK4 2007
6 AB3 2009
7 AB3 2009
8 AB1 2007
9 AB1 2000
10 CD2 2010
I want to add a column xp with the number of rows that match ID and have a smaller value of year than the current row. I am looking for something like that:
df$xp <- nrow( ID == "ID in current row" & year < "year in current row" )
The result should be:
ID year xp
1 AB1 2005 1
2 AB1 2008 3
3 CD2 2005 0
4 AB3 2010 2
5 KK4 2007 0
6 AB3 2009 0
7 AB3 2009 0
8 AB1 2007 2
9 AB1 2000 0
10 CD2 2010 1