Here is an example:
set.seed(123) data<-data.frame(X=rep(letters[1:3], each=4),Y=sample(1:12,12),Z=sample(1:100, 12)) data[data==3]<-NA
There is a data.table way
data.table
library(data.table) set.seed(123) data<-data.frame(X=rep(letters[1:3], each=4),Y=sample(1:12,12),Z=sample(1:100, 12)) data[data==3]<-NA data <- data.table(data) data[data[,.I[which.min(Y)], by = "X"][,V1]]