If I understood your question right -
library(data.table)
# some random data
dt <- data.table(
year = c(rep(2013,4),rep(2012,4),rep(2011,4)),
country = rep(c('A','B','C','D'),3),
growth_rate = runif(12,0,10)
)
# country to compare
countrycompared <- 'B'
# creating the new dataset where growth rate is higher that country to compare in that year
dt2 <- dt[,
ToKeep := growth_rate > .SD[country == countrycompared,growth_rate
],
by = year][ToKeep == TRUE]
This is what dt
looks like -
> dt
year country growth_rate
1: 2013 A 3.175187
2: 2013 B 3.693736
3: 2013 C 4.080300
4: 2013 D 9.692282
5: 2012 A 7.212747
6: 2012 B 8.343452
7: 2012 C 6.606016
8: 2012 D 8.516030
9: 2011 A 6.361843
10: 2011 B 8.318292
11: 2011 C 4.682559
12: 2011 D 2.081757
And dt2
-
> dt2
year country growth_rate ToKeep
1: 2012 A 4.038502 TRUE
2: 2012 D 8.113058 TRUE