【问题标题】:Match two files with recency of date in r在 r 中匹配两个具有最近日期的文件
【发布时间】:2020-08-20 11:24:10
【问题描述】:

我的数据如下:

FileA <- data.frame(
         Item = c(101,102,103,104,105),
         Date = as.Date(c("2020-08-17","2020-07-15","2020-06-17","2020-04-17","2020-04-12")),
         Price =c(5,6,7,8,9))
FileB <- data.frame(
  Item = c(101,101,102,103,103),
  Date = as.Date(c("2020-08-01","2020-08-16","2020-05-17","2020-03-10","2019-05-12")),
  Price =c(15,16,17,18,19))

项目 101、102 和 103 都存在于两个不同的数据帧中。我想根据项目从 FileA 匹配到 FileB,并且同一项目的最近日期是 FileB。

例如:FileA 中的“Item 101”应与 FileB 中日期为“2020-08-16”的“Item 101”匹配(因为它比 File'A'中的“Item 101”日期更近) ) 并且与“2020-08-01”不匹配。

输出应该是这样的:

【问题讨论】:

    标签: r


    【解决方案1】:

    这是使用roll = "nearest"data.table 方法:

    FileA <- data.frame(
      Item = c(101,102,103,104,105),
      Date = as.Date(c("2020-08-17","2020-07-15","2020-06-17","2020-04-17","2020-04-12")),
      Price =c(5,6,7,8,9))
    FileB <- data.frame(
      Item = c(101,101,102,103,103),
      Date = as.Date(c("2020-08-01","2020-08-16","2020-05-17","2020-03-10","2019-05-12")),
      Price =c(15,16,17,18,19))
    
    
    library(data.table)
    setDT(FileA)
    setDT(FileB)
    
    FileB[, Date_B := Date][, Item_Code_B := Item]
    resultDT <- na.omit(FileB[FileA, on = c("Item", "Date"), roll = "nearest"])
    
    setnames(resultDT, c("Item", "Date", "Price", "i.Price"), c("Item_Code_A", "Date_A", "Price_A", "Price_B"))
    setcolorder(resultDT, c("Item_Code_A", "Date_A", "Price_A", "Item_Code_B", "Date_B", "Price_B"))
    
    resultDT
    

    > resultDT
       Item_Code_A     Date_A Price_A Item_Code_B     Date_B Price_B
    1:         101 2020-08-17       5         101 2020-08-16      16
    2:         102 2020-07-15       6         102 2020-05-17      17
    3:         103 2020-06-17       7         103 2020-03-10      18
    

    您可以使用setDF(resultDT) 将结果转换回“正常”数据帧。

    【讨论】:

    • 工作,谢谢:)。有没有办法对基本功能做同样的事情,因为我正在使用 sparkr(spark data frame) data.table doesn't work there
    • 肯定可以在基础 R 中使用(但可能不太方便)。也许this 有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 2022-06-28
    • 1970-01-01
    • 2020-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多