所以我有一个国家人均国民总收入和自杀数字的数据集,我正在尝试仅过滤国民总收入最高的前 10 个国家。我的问题是,在我的数据集中,我有重复的 GNI 国家条目,因为我还有每个国家/地区每个性别特定年龄组的自杀统计数据。

我尝试使用 Dplyr 中的 top_n 函数应用以下代码:

top_highest_gni <- df_filter_ages %>%   group_by(as.numeric(as.character(GNI.per.capita..PPP..current.international.....NY.GNP.PCAP.PP.CD.))) %>%
      top_n(10)

但是,这根本不会影响我的数据集,也没有出现错误消息,我不知道为什么?对此的任何帮助将不胜感激!

数据如下所示:
Country   Year   Sex  GNI
Albania   2012   F    290000
Albania   2012   M    290000
UK        2012   F    2222222222
UK        2012   M    2222222222

编辑

按照建议,我添加了汇总功能并运行了以下代码:
df_filter_ages %>%
  group_by(country) %>%
  summarise(max = max(as.numeric(as.character(GNI.per.capita..PPP..current.international.....NY.GNP.PCAP.PP.CD.)))) %>%
  top_n(2)

输出是:
Selecting by max
     max
1 119330

所需的输出:
Country   Year   Sex  GNI

UK        2012   F    2222222222
UK        2012   M    2222222222
Albania   2012   F    290000
Albania   2012   M    290000

最佳答案

尝试在 summarise() 函数之后和 group_by() 函数之前包含 top_n() 函数。

例子:

df <- data.frame(x = c(1, 2, 3),
                 y = c(4, 5, 6),
                 z = c(1, 20, 50))

df %>%
  group_by(x) %>%
  summarise(max = max(z)) %>%
  top_n(2)

#  A tibble: 2 x 2
#       x total
#   <dbl> <dbl>
# 1     2    20
# 2     3    50

关于r - 尝试使用 R 过滤前 10 个条目?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55785226/

10-10 14:08
查看更多