[R] Unique Pairs based on a Minimum Value

jim holtman jholtman at gmail.com
Tue Nov 6 01:54:25 CET 2007


Here is one way of doing it:

> z <- as.data.frame(cbind(x, y))
> a <- by(z, z$x, function(b) b[which.min(b$y),])
> do.call('rbind', a)
    x   y
10 10 112
12 12 111
13 13 117
15 15 114
16 16 113
17 17 119
>


On 11/5/07, Bret Collier <bacollier at ag.tamu.edu> wrote:
> RUsers,
>
> I am trying (with little success) to determine how to combine unique and
> min to do some data frame manipulations and I could use a little advice.
>  I have tried various combinations of 'unique', 'min' and 'apply' with
> no luck.
>
> Given this simple example data (x, y)
>
> x<-c(10, 10, 12, 13, 15, 16 ,17, 17, 17)
> y<-c(112, 117, 111, 117, 114, 113, 119, 121, 130)
>
> as.data.frame(cbind(x, y))
>
>    x   y
> 1 10 112
> 2 10 117
> 3 12 111
> 4 13 117
> 5 15 114
> 6 16 113
> 7 17 119
> 8 17 121
> 9 17 130
>
> I have been attempting to get all those unique 'x-y' combinations for
> which the y column is the minimum of the values y takes for each unique
> x (ID variable), such as below.
>
>    x   y
> 1 10 112
> 3 12 111
> 4 13 117
> 5 15 114
> 6 16 113
> 7 17 119
>
> Any advice/directions I could look would be appreciated.
>
> TIA,
> Bret
> R 2.6.0; platform i386-pc-mingw32
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>


-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?



More information about the R-help mailing list