【问题标题】:Select unique values in dataframe based on sorted value根据排序值选择数据框中的唯一值
【发布时间】:2019-05-22 20:17:34
【问题描述】:

有没有人根据第二个值的最大值从数据框中选择唯一值?

例子:

name value
cheese 15
pepperoni 12
cheese 9
tomato 4
cheese 3
tomato 2

我想出的最好的方法——我确信有更好的方法——是按值降序对 df 进行排序,提取 df$name,在其上运行 unique(),然后使用 dplyr 进行左连接。

理想的结果是这样的:

name value
cheese 15
pepperoni 12
tomato 4

提前致谢!

【问题讨论】:

    标签: r sorting filter dplyr data.table


    【解决方案1】:

    看到您的预期结果,对于每个name,您正在寻找具有最大数字的行。完成此任务的一种方法如下。

    library(dplyr)
    group_by(mydf, name) %>%
    slice(which.max(value))
    
    # A tibble: 3 x 2
    # Groups:   name [3]
    #  name      value
    #  <fct>     <int>
    #1 cheese       15
    #2 pepperoni    12
    #3 tomato        4
    

    数据

    mydf <- structure(list(name = structure(c(1L, 2L, 1L, 3L, 1L, 3L), .Label = c("cheese", 
    "pepperoni", "tomato"), class = "factor"), value = c(15L, 12L, 
    9L, 4L, 3L, 2L)), class = "data.frame", row.names = c(NA, -6L
    ))
    

    【讨论】:

    • 这比我想做的要简单得多 - 谢谢!
    • @ChristopherPenn 很高兴为您提供帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-05
    • 1970-01-01
    • 2014-03-24
    • 2021-12-24
    相关资源
    最近更新 更多