[R] Sorting data frame by prepared order

JS Huang js.huang at protective.com
Tue Mar 3 01:07:22 CET 2015


Here is an implementation.

> t <-
> data.frame(x=c(1,1,1,1,1,2,2,2,2,2),y=c("a","a","a","b","b","a","a","b","b","b"))
> t
   x y
1  1 a
2  1 a
3  1 a
4  1 b
5  1 b
6  2 a
7  2 a
8  2 b
9  2 b
10 2 b
> assignSeq
function(test)
{
  temp <- test[order(test$x),]
  InC <- numeric(length(test))
  inD <- unique(test$x)
  countAll <- 0
  for (i in 1:length(inD))
  {
    countA <- 0
    countB <- 0
    for (j in 1:dim(temp[temp$x==inD[i],])[1])
    {
      countAll <- countAll + 1
      if (temp$y[countAll] == "a")
      {
        InC[countAll] <- 2*countA
        countA <- countA + 1
      }
      else
      {
        InC[countAll] <- 2*countB + 1
        countB <- countB + 1
      }
    }
  }
  temp$seq <- InC
  return(temp)
}
> d <- assignSeq(t)
> d[order(d$x,d$seq),-3]
   x y
1  1 a
4  1 b
2  1 a
5  1 b
3  1 a
6  2 a
8  2 b
7  2 a
9  2 b
10 2 b



--
View this message in context: http://r.789695.n4.nabble.com/Sorting-data-frame-by-prepared-order-tp4704038p4704092.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list