[R] Computing an ordering on subsets of a data frame
jim holtman
jholtman at gmail.com
Thu Apr 19 04:54:22 CEST 2007
Does this do what you want?
> x <- "A B
+ 1 2
+ 1 3
+ 1 4
+ 2 3
+ 2 1
+ 2 1
+ 3 2
+ 3 1
+ 3 3"
> x <- read.table(textConnection(x), header=TRUE)
> x$C <- ave(x$B, x$A, FUN=rank)
> x
A B C
1 1 2 1.0
2 1 3 2.0
3 1 4 3.0
4 2 3 3.0
5 2 1 1.5
6 2 1 1.5
7 3 2 2.0
8 3 1 1.0
9 3 3 3.0
On 4/18/07, Lukas Biewald <lukeb at powerset.com> wrote:
> If I have a data frame X that looks like this:
>
> A B
> - -
> 1 2
> 1 3
> 1 4
> 2 3
> 2 1
> 2 1
> 3 2
> 3 1
> 3 3
>
> and I want to make another column which has the rank of B computed
> separately for each value of A.
>
> I.e. something like:
>
> A B C
> - - -
> 1 2 1
> 1 3 2
> 1 4 3
> 2 3 3
> 2 1 1
> 2 1 2
> 3 2 2
> 3 1 1
> 3 3 3
>
> by(X, X[,1], function(x) { rank(x[,1], ties.method="random") } ) almost
> seems to work, but the data is not in a frame, and I can't figure out how to
> merge it back into X properly.
>
> Thanks,
> Lukas
>
> ______________________________________________
> R-help at stat.math.ethz.ch 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