Hi Lukas,
Using by() or its cousins tapply() etc. is tricky,
as you need to properly merge results back into X.
You can do that by adding a key ID variable to X,
and carrying along that key ID variable in calls
to by() etc., though I haven't tested out a method.
You can also create a new
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],
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