sort and number within levels of a factor in r
r
Solution
There are many ways to skin this cat. Here is one solution using base R and vectorized code in two steps (without any `apply`):
- Sort the data using `order` and `xtfrm`
- Use `rle` and `sequence` to genereate the sequence.
Replicate your data:
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)
Two lines of code:
r <- dat[order(dat$type, -xtfrm(dat$x)), ]
r$y <- sequence(rle(r$type)$lengths)
Results in:
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
The call to `order` is slightly complicated. Since you are sorting one column in ascending order and a second in descending order, use the helper function `xtfrm`. See `?xtfrm` for details, but it is also described in `?order`.
Problem
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 ``` I.e. i want to sort the whole data frame within the levels of factor `type` based on vector `x`. Get the length of of each level `a = 3 b=2 c=1` and then number in a decreasing fashion in a new vector `y`. My starting place is currently with `sort()` ``` tapply(y, x, sort) ``` Would it be best to first try and use sapply to split everything first?