【问题标题】:Getting all the corresponding rows with max date in r在r中获取所有具有最大日期的相应行
【发布时间】:2016-05-29 11:43:15
【问题描述】:

我有与此类似的数据框,但还有 30 个变量

我只需要每个“代码”对应的最大日期值 所以输出应该是这样的

请任何专家帮助我解决这个问题。

【问题讨论】:

    标签: r max


    【解决方案1】:

    也可以使用dplyr 来完成(假设您的数据是一个名为dt 的数据框):

    library(dplyr)
    
    dt %>% group_by(code) %>% filter(Date == max(Date))
    

    【讨论】:

    • 嗨大卫,非常感谢它的工作。你能解释一下代码是如何工作的
    • 首先是使用“管道”%>%,它使您能够链接命令。这使得代码更容易编写和阅读。因此,您首先指定数据框的名称,然后将其“传送”到链中的下一个命令group_by。此命令根据code 的值将数据拆分为多个块,因此链中的所有后续命令一次处理一个块,结果组合在返回的数据中。 filter用于根据条件选择数据中的行,因此选择每个chunk中最新日期对应的行。
    【解决方案2】:

    我们可以使用data.table。将'data.frame'转换为'data.table'(setDT(df1)),按'code'分组,我们order'Date'降序得到head的第一行。

    library(data.table)
    setDT(df1)[order(-as.Date(Date, '%m/%d/%Y')), head(.SD, 1), by = code]
    #       code bill      Date Type Month   KM
    #1: C111574885   50 9/25/2015  red     9 1070
    #2: C111519730  200 6/25/2015 blue     6  350
    #3: D100000468   40  6/4/2015  red     6 1240
    #4: D100000470  500 3/13/2015  red     3 1000
    

    或者在ordering 之后,我们可以使用unique by 'code' 来获取第一行(将有最大日期)。

    unique(setDT(df1)[order(code, -as.Date(Date, '%m/%d/%Y'))], by = 'code')
    #  bill       code      Date Type Month   KM
    #1:  200 C111519730 6/25/2015 blue     6  350
    #2:   50 C111574885 9/25/2015  red     9 1070
    #3:   40 D100000468  6/4/2015  red     6 1240
    #4:  500 D100000470 3/13/2015  red     3 1000
    

    数据

    df1 <-  structure(list(bill = c(100, 200, 500, 900, 150, 50, 40), 
    code = c("C111519730", 
    "C111519730", "D100000470", "C111574885", "C111574885", "C111574885", 
    "D100000468"), Date = c("4/9/2015", "6/25/2015", "3/13/2015", 
    "1/9/2015", "9/20/2015", "9/25/2015", "6/4/2015"), Type = c("red", 
    "blue", "red", "red", "blue", "red", "red"), Month = c(4, 6, 
    3, 1, 9, 9, 6), KM = c(100, 350, 1000, 450, 900, 1070, 1240)),
     .Names = c("bill", 
    "code", "Date", "Type", "Month", "KM"),
     row.names = c(NA, -7L), class = "data.frame")
    

    【讨论】:

    • @Sotos 是的,它应该也可以,但是order 可能更快
    • 这个解决方案超级慢。
    • @marbel 您可以使用.I 来加快速度,而不是使用.SD 进行子集化
    • 即setDT(df1)[df1[order(-as.Date(Date, '%m/%d/%Y')), .I[1], by = code]$V1]
    • @marbel 是的,它只返回另一列中的索引(默认列以'V1'开头。所以我们提取$V1。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    • 2015-02-25
    • 2021-04-01
    • 1970-01-01
    相关资源
    最近更新 更多