Here is an example about what I want:
set.seed(123)
data<-data.frame(X=rep(letters[1:3], each=4),Y=sample(1:12,12),Z=sample(1:100, 12))
setDT(data)
What I would like to do is to select the unique row of X with minimum Y and the next closer value to the minimum
Desired output
>data
a 4 68
a 5 11
b 1 4
b 10 89
c 2 64
c 3 82
The min value is already answer in this post How to select rows by group with the minimum value and containing NAs in R
data[, .SD[which.min(Y)], by=X]
But how to do it with the minimum and the next closer?