[英]Sort out specific levels in one column according to the values in another column
I just came into R so I am stuck in a very basic question.我刚刚进入 R 所以我陷入了一个非常基本的问题。
Right now I have a dataset listing soccer players and their goals, I have reordered the goals in descending order, now I need to find the top five players according to their goals.现在我有一个列出足球运动员及其目标的数据集,我已经按降序重新排列了目标,现在我需要根据他们的目标找到前五名球员。
the dataset looks like this:数据集如下所示:
Player Goals
A 10
A 10
B 10
C 9
B 8
C 7
A 7
D 6
E 6
F 5
How can I sort out the top 5 players using the dplyr
package?如何使用
dplyr
package 排序前 5 名玩家?
Try this one.试试这个。 If you could provide your data with
dput()
we could improve the code, Note: You have got ties in your dataset:如果您可以使用
dput()
提供数据,我们可以改进代码,注意:您的数据集中有关联:
library(dplyr)
df %>%
distinct() %>%
top_n(5 )
OR或者
df %>%
distinct() %>%
slice_max(Goals, n=5)
Player Goals
1 A 10
2 B 10
3 C 9
4 B 8
5 C 7
6 A 7
Another dplyr
option:另一个
dplyr
选项:
df <- read.table(text="Player Goals
A 10
A 10
B 10
C 9
B 8
C 7
A 7
D 6
E 6
F 5", header = TRUE)
library(dplyr)
df %>%
arrange(desc(Goals)) %>%
distinct() %>%
filter(row_number() <= 5L)
#> Player Goals
#> 1 A 10
#> 2 B 10
#> 3 C 9
#> 4 B 8
#> 5 C 7
Created on 2022-07-01 by the reprex package (v2.0.1)由代表 package (v2.0.1) 于 2022 年 7 月 1 日创建
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.