Sort and number within factor levels r

if I have the following data frame G:

z    type   x   
1     a     4
2     a     5 
3     a     6
4     b     1
5     b     0.9
6     c     4

I am trying to get:

z    type   x   y
3     a     6   3
2     a     5   2
1     a     4   1
4     b     1   2
5     b     0.9 1
6     c     4   1

those. I want to sort the entire data frame within factor levels typebased on a vector x. Get the length of each level a = 3 b=2 c=1, and then decrease the number in the new vector y.

My starting place currently has sort()

tapply(y, x, sort)

Would it be better to try and use sapply first to smash everything first?

+3
source share
2 answers

There are many ways to trick this cat. Here is one solution using the R base and vectorized code in two steps (without apply):

  • Sort data using orderandxtfrm
  • rle sequence .

:

dat <- read.table(text="
z    type   x   
1     a     4
2     a     5 
3     a     6
4     b     1
5     b     0.9
6     c     4
", header=TRUE, stringsAsFactors=FALSE)

:

r <- dat[order(dat$type, -xtfrm(dat$x)), ]
r$y <- sequence(rle(r$type)$lengths)

:

r
  z type   x y
3 3    a 6.0 1
2 2    a 5.0 2
1 1    a 4.0 3
4 4    b 1.0 1
5 5    b 0.9 2
6 6    c 4.0 1

order . , xtfrm. . ?xtfrm, ?order.

+7

:

dat <- read.table(text="z    type   x   
1     a     4
2     a     5 
3     a     6
4     b     1
5     b     0.9
6     c     4", header=T)

:

dat <- dat[order(dat$type), ]
x <- by(dat, dat$type, nrow)
dat$y <- unlist(sapply(x, function(z) z:1))

, , . , , .

+4

All Articles