简体   繁体   English

根据另一列中的值对一列中的特定级别进行排序

[英]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.

相关问题 根据另一列的级别对数​​据框中的列进行排序 - sort column in data frame according to levels of another column 如何根据另一列中值的出现设置因子水平顺序? - How to set factor levels order according to appearance of values in another column? 根据另一列中的因子级别更改一列中的数值 - Change numeric values in one column based on factor levels in another column 根据r中的ID从一列中查找另一列中的值 - Find values from one column in another column according to ID in r 根据另一列中的行信息替换一列中的不同值 - Replace different values in one column, according to the row information in another column 如何根据另一列中的特定日期和级别为列分配级别? - How to assign levels to a column based on specific dates and levels in another column? 计算一列中的唯一值,计算另一列中的特定值, - count unique values in one column for specific values in another column, 根据一列排名并分组另一列 - Rank according to one column and grouby another column 对于另一列的所有级别,R通过一列的值提取第n个最低值 - R extract the n-th lowest value by values of one column, for all the levels of another column 使用 case_when() 和 filter() 根据 R 中一列中的值和另一列中的级别对数​​据框进行子集化 - using case_when() and filter() to subset a dataframe based on values in one column and levels in another column in R
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM