gpt4 book ai didi

r - 如何根据另一列定义的组计算一列的排名?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:50:41 26 4
gpt4 key购买 nike

Windows 7 上的 R 版本 2.11.1 32 位

我得到如下数据集:

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

USER_A 为 1:3,USER_B 为 6:10。现在我需要输出 USER_A 和 USER_B 的 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)

其实我只需要输出排名即可:

3 1 2
2 1
1 2

因为每一行的长度不一样,所以很不爽!我无法将它们存储在矩阵中然后输出它们。

谁能帮我解决这个问题?

最佳答案

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)

一种方法是拆分数据:

sdf <- with(df, split(SCORE, f = USER_A))
lapply(sdf, rank)

最后一行给出:

> lapply(sdf, rank)
$`1`
[1] 3 1 2

$`2`
[1] 2 1

$`3`
[1] 1 2

另一种方法是使用 aggregate(),如下所示:

aggregate(SCORE ~ USER_A, data = df, rank)

哪个返回:

> (foo <- aggregate(SCORE ~ USER_A, data = df, rank))
USER_A SCORE
1 1 3, 1, 2
2 2 2, 1
3 3 1, 2

但是这里的输出有点不同,现在我们有一个数据框,第二个组件 SCORE 是一个列表,就像输出的 lapply() 版本一样:

> 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

关于r - 如何根据另一列定义的组计算一列的排名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5648763/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com