How to calculate ranking of one column based on groups defined by another column?
R Version 2.11.1 32-bit on Windows 7
I get a data set as below:
USER_A USER_B SCORE
1 6 0.2
1 7 0.1
1 10 0.15
2 6 0.2
2 9 0.12
3 8 0.15
3 9 0.3
the USER_A is 1:3 and the USER_B is 6:10. Now I need to output the USER_A with the ranking of USER_B by their SCORE:
开发者_运维技巧USER_A ranking of USER_B
1 3 1 2 #the ranking of USER_B 6,7,10(which belong to USER_A 1)
2 2 1 #the ranking of USER_B 6,9(which belong to USER_A 2)
3 1 2 #the ranking of USER_B 8,9(which belong to USER_A 3)
in fact, I just need to output the ranking:
3 1 2
2 1
1 2
it is upset because the length of each row is different! I could not store them in a matrix and then output them.
Could anyone help me solve this problem?
df <- read.table(con <- textConnection("USER_A USER_B SCORE
1 6 0.2
1 7 0.1
1 10 0.15
2 6 0.2
2 9 0.12
3 8 0.15
3 9 0.3
"), header = TRUE)
close(con)
One way is to split the data:
sdf <- with(df, split(SCORE, f = USER_A))
lapply(sdf, rank)
The last line gives:
> lapply(sdf, rank)
$`1`
[1] 3 1 2
$`2`
[1] 2 1
$`3`
[1] 1 2
An alternative is to use aggregate()
as in:
aggregate(SCORE ~ USER_A, data = df, rank)
Which returns:
> (foo <- aggregate(SCORE ~ USER_A, data = df, rank))
USER_A SCORE
1 1 3, 1, 2
2 2 2, 1
3 3 1, 2
But the output is a bit different here, now we have a data frame, with the second component SCORE
being a list, just like the lapply()
version outputted:
> str(foo)
'data.frame': 3 obs. of 2 variables:
$ USER_A: int 1 2 3
$ SCORE :List of 3
..$ 0: num 3 1 2
..$ 1: num 2 1
..$ 2: num 1 2
> foo$SCORE
$`0`
[1] 3 1 2
$`1`
[1] 2 1
$`2`
[1] 1 2
精彩评论