Skip to content
Prev 11630 / 398502 Next

ranking the difference of two columns in a dataframe by groups

First: I'm (as usual) unsure if I understood you right
Second: The grouping thing should be trivial
Third: For the rest, this might give you a hint:

xx <- data.frame(g=sort(rep(1:3,len=20)),x=rnorm(20,10,10),y=rnorm(20,10,10))
xx <- xx[order(xx$g,xx$y-xx$x),]
xx$New <- unlist(by(xx[,c("x","y")],xx$g,function(x){
  WhichMin <- which.min(abs(x[,1]-x[,2]))
  Len <- length(x[,1])
  if(WhichMin>1) Lower <- sort(-(seq(0,WhichMin-1,1)))
  else Lower <- 0
  Upper <- seq(WhichMin+1,Len,1)-WhichMin
  c(Lower,Upper)
    
})
                 )
xx$Diff <- xx$y-xx$x
xx

Peter
On Thu, Jun 07, 2001 at 09:21:55PM -0500, Jeff Miller wrote:

  
    
Message-ID: <20010608105207.B8299@rzpool01.pool.rz.tu-bs.de>
In-Reply-To: <001001c0efc1$eb71bc40$cee7fea9@x2t9h6>; from jdm@xnet.com on Thu, Jun 07, 2001 at 09:21:55PM -0500