【问题标题】:Dataframe: descending sorting not working数据框:降序排序不起作用
【发布时间】:2018-06-23 21:41:47
【问题描述】:

我有一个数据框:

CityVsPrice=data.frame(City,Price)

City      Price

New York  10000
New York  15000
New York  12000
Madison   800
Lodi      8000
Chico     9000
Redlands  200

然后我希望按价格对这个列表进行排序,给出价格最高的 3 个城市。所以理想情况下,纽约只会出现一次,其次是奇科,然后是洛迪。也许另一种解决方法是为每个城市取最高值,然后按降序排序并选择前 3 个。有什么简单的方法吗?

提前致谢!

【问题讨论】:

    标签: r


    【解决方案1】:

    tidyverse 做得很好,你会喜欢的 :)

    https://dplyr.tidyverse.org/

    library(dplyr)
    data.frame(City,Price) %>% 
      group_by(City) %>% 
      top_n(1, Price) %>% 
      ungroup() %>% 
      top_n(3, Price)
    

    【讨论】:

    • 不,它没有。可能存在命名混淆。例如。 City 同时是一个 data.frame 和一个列名。这可以解决 CityVsPrice
    【解决方案2】:

    所以,这终于奏效了:

    Price=as.numeric(as.character(Price))
    
    ByPrice<- data.frame(aggregate(Price ~ City, data = CityVsPrice, max))
    

    【讨论】:

      【解决方案3】:

      有一些方法可以在基本 R 中简洁地做到这一点,但这里有一个使用 data.table 的解决方案:

      setDT(CityVsPrice)[, .(Price = max(Price)), by=City][order(-Price)][1:3]
             City Price
      1: New York 15000
      2:    Chico  9000
      3:     Lodi  8000
      

      【讨论】:

        猜你喜欢
        • 2014-05-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-21
        • 1970-01-01
        相关资源
        最近更新 更多