Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
589 views
in Technique[技术] by (71.8m points)

r - Matching timestamped data to closest time in another dataset. Properly vectorized? Faster way?

I have a timestamp in one data frame that I am trying to match to the closest timestamp in a second dataframe, for the purpose of extracting data from the second dataframe. See below for a generic example of my approach:

library(lubridate)

data <- data.frame(datetime=ymd_hms(c('2015-04-01 12:23:00 UTC', '2015-04-01 13:49:00 UTC', '2015-04-01 14:06:00 UTC' ,'2015-04-01 14:49:00 UTC')),
                   value=c(1,2,3,4))
reference <- data.frame(datetime=ymd_hms(c('2015-04-01 12:00:00 UTC', '2015-04-01 13:00:00 UTC', '2015-04-01 14:00:00 UTC' ,'2015-04-01 15:00:00 UTC', '2015-04-01 16:00:00 UTC')),
                        refvalue=c(5,6,7,8,9))

data$refvalue <- apply(data, 1, function (x){
  differences <- abs(as.numeric(difftime(ymd_hms(x['datetime']), reference$datetime)))
  mindiff <- min(differences)
  return(reference$refvalue[differences == mindiff])
})

data
#              datetime value refvalue
# 1 2015-04-01 12:23:00     1        5
# 2 2015-04-01 13:49:00     2        7
# 3 2015-04-01 14:06:00     3        7
# 4 2015-04-01 14:49:00     4        8

This works fine, except it is very slow, because the reference dataframe is quite large in my real-world application. Is this code properly vectorized? Is there a faster, more elegant way of performing this operation?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can try data.tables rolling join using the "nearest" option

library(data.table) # v1.9.6+
setDT(reference)[data, refvalue, roll = "nearest", on = "datetime"]
# [1] 5 7 7 8

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...