【问题标题】:Searching for nearest date in data frame在数据框中搜索最近的日期
【发布时间】:2014-02-06 15:37:13
【问题描述】:

我有两个数据框:

purchases:

                time        quantity
  1: 2013-07-31 03:42:02    30       
  2: 2013-07-31 03:59:32    30        
  3: 2013-07-31 04:02:22    28       
  ....

history:

                time        price
  1: 2013-07-31 04:26:46   10
  2: 2013-07-31 07:11:01    10
  3: 2013-07-31 08:16:36     5
  4: 2013-07-31 08:40:03     8
  5: 2013-07-31 08:47:56     7
  ....

我想做什么: 对于“purchases”中的每一行,在“history”中查找日期最近的行(如果可能小于“purchases”中的行)

我试图做这样的事情

history <- as.vector(history$time)

对于购买中的每一行:

current.price <- purchases[i,]$time
which(history-current.price)==min(history-current.price)

如果值是数字,这很有用,但我不知道如何处理 POSIXct 类的这些日期。

编辑:添加了可重现的数据

#Reproducible dummy data
p <- read.table(text="
t,quantity
2013-07-31 03:42:02,30
2013-07-31 03:59:32,30
2013-07-31 04:02:22,28",header=TRUE,sep=",")
h <- read.table(text="
t,price
2013-07-31 04:26:46,10
2013-07-31 07:11:01,10
2013-07-31 08:16:36,5
2013-07-31 08:40:03,8
2013-07-31 08:47:56,7",header=TRUE,sep=",")
#Convert to POSIXct
p$t <- as.POSIXct(strptime(p$t, "%Y-%m-%d %H:%M:%S"))
h$t <- as.POSIXct(strptime(h$t, "%Y-%m-%d %H:%M:%S"))

【问题讨论】:

  • 试试difftime?
  • 使用 data.tables 进行滚动连接?
  • 添加了可重现的数据,以防有人想尝试...

标签: r date posixct


【解决方案1】:

这是使用difftime 的解决方案。我已经更新了您的示例,使某些行的日期晚于历史表中的日期。

#Reproducible dummy data
p <- read.table(text="
t,quantity
2013-07-31 03:42:02,30
2013-07-31 03:59:32,30
2013-07-31 04:02:22,28
2013-07-31 04:40:22,28
2013-07-31 05:50:22,28
2013-07-31 08:40:22,28",header=TRUE,sep=",")
h <- read.table(text="
t,price
2013-07-31 04:10:46,10
2013-07-31 04:35:46,10
2013-07-31 07:11:01,10
2013-07-31 08:16:36,5
2013-07-31 08:40:03,8
2013-07-31 08:47:56,7",header=TRUE,sep=",")
#Convert to POSIXct
p$t <- as.POSIXct(strptime(p$t, "%Y-%m-%d %H:%M:%S"))
h$t <- as.POSIXct(strptime(h$t, "%Y-%m-%d %H:%M:%S"))


get_closest_line_in_history <- function(x, history){
  time_diffs <- difftime(x, history)
  time_diffs[time_diffs<0] <- NA

  res <- which.min(time_diffs)
  if (length(res) != 1){
    return(NA)
  }else{
    return(res)
  }
}

sapply(p$t, get_closest_line_in_history, h$t)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-26
    • 2019-04-28
    • 1970-01-01
    • 2013-06-18
    • 2022-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多