This is directly related to the question asked in Extract all rows containing first value for each unique value of another column
but instead of returning the first year an ID was detected, I want to return all rows with only the second year.
Adapting the answers in the above thread from
test
ID yr
1 54V 1
2 54V 1
3 54V 1
4 54V 2
5 54V 2
6 56V 2
7 56V 2
8 56V 3
9 59V 1
10 59V 2
11 59V 3
to
test2 <- test[with(test, as.logical(ave(yr, ID, FUN = function(x) x==x[2L]))),]
or
test2 <- setDT(test)[, .SD[yr==yr[2L]], ID]
produces strange results.
ID yr
1 54V 1
2 54V 1
3 54V 1
5 56V 2
6 56V 2
9 59V 2
My desired result would be
ID yr
4 54V 2
5 54V 2
8 56V 3
10 59V 2
What am I doing wrong?