dplyr的top_n()为什么不起作用? [英] Why won't dplyr's top_n() work?

查看:59
本文介绍了dplyr的top_n()为什么不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 df 的数据框:

I have a dataframe called df:

City,State,Price,Dogs
Portland,OR,75,1
Portland,OR,100,3
San Diego,CA,12,4
San Diego,CA,23,5
...

我使用了 dplyr summaryise group_by 函数...

I used dplyr's summarise and group_by functions...

df.median <- summarise(
  group_by(
    df, 
    State, 
    City
  ),
  MEDIAN_PRICE = median(Price),
  SUM_DOGS = sum(Dogs)
)

但是当我运行 top_n(df.median,100,SUM_DOGS)时,R不会为我提供 SUM_DOGS 中最高100的城市.它只返回 df.median .

But when I run top_n(df.median, 100, SUM_DOGS), R does not give me cities with the 100 highest values in SUM_DOGS. It just returns df.median.

为什么?

推荐答案

您可能需要 ungroup ,所以您从整个数据集中选择 top_n ,而不是<每个州的code> top_n (因为您的数据集目前已分组).

You likely need to ungroup, so you pick the top_n from the whole dataset rather than the top_n from each State (as your dataset is currently grouped).

top_n(ungroup(df.median), 100, SUM_DOGS)

这篇关于dplyr的top_n()为什么不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆