How to select rows by group with the minimum value and containing NAs in R

前端 未结 4 589
悲哀的现实
悲哀的现实 2021-01-20 01:55

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
         


        
4条回答
  •  囚心锁ツ
    2021-01-20 02:22

    There is a data.table way

    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]]
    

提交回复
热议问题