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

前端 未结 4 588
悲哀的现实
悲哀的现实 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:26

    This does not select the rows using an index but returns the values you want...

    ddply(data, .(X), summarise, min=min(Y, na.rm=T))
    
      X min
    1 a   5
    2 b   1
    3 c   4
    

    EDIT AFTER COMMENT: To select the whole rows you may:

    ddply(data, .(X), function(x) arrange(x, Y)[1, ])
    
      X Y  Z
    1 a 4 68
    2 b 1  4
    3 c 2 64
    

    Or

    data$index <- 1L:nrow(data)
    i <- by(data, data$X, function(x) x$index[which.min(x$Y)] )
    data[i, ]
    
       X Y  Z index
    1  a 4 68     1
    6  b 1  4     6
    10 c 2 64    10
    

提交回复
热议问题