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

dataframe, na, r

Solution

Using the `data.table` package, this is trivial:

library(data.table)

d <- data.table(data)
d[, min(Y, na.rm=TRUE), by=X]

You can also use `plyr` and its `ddply` function:

library(plyr)

ddply(data, .(X), summarise, min(Y, na.rm=TRUE))

Or using base R:

aggregate(X ~ ., data=data, FUN=min)

Based on the edits, I would use `data.table` for sure:

d[, .SD[which.min(Y)], by=X]

However, there are solutions using base R or other packages.

Problem

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 ``` What I am to realize is to select the unique row of `X` with minimum `Y` by ignoring `NA`s: ``` a 4 68 b 1 4 c 2 64 ``` What's the best way to do that?

Original source