Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

r - Lookup values corresponding to the closest date

I have a data.frame x with date and Value

x = structure(list(date = structure(c(1376534700, 1411930800, 1461707400, 
1478814300, 1467522000, 1451088000, 1449956100, 1414214400, 1472585400, 
1418103000, 1466176500, 1434035100, 1442466300, 1410632100, 1448571900, 
1439276400, 1468382700, 1476137400, 1413177300, 1438881300), class = c("POSIXct", 
"POSIXt"), tzone = ""), Value = c(44L, 49L, 31L, 99L, 79L, 92L, 
10L, 72L, 60L, 41L, 28L, 21L, 67L, 61L, 8L, 65L, 40L, 48L, 53L, 
90L)), .Names = c("date", "Value"), row.names = c(NA, -20L), class = "data.frame")

and another list y with only date

y = structure(c(1470356820, 1440168960, 1379245020, 1441582800, 1381753740
), class = c("POSIXct", "POSIXt"), tzone = "")

Before I try to do it with a loop, I wanted to find out if there is a quick way (or packages) to lookup Value from the closest date in x for dates in y? The goal is to find out a date in x that is closest to the date in y and obtain the corresponding Value.

The desired output (got from Excel VLOOKUP, so may not be perfect) would be something like:

output = structure(list(y = structure(c(1470356820, 1440168960, 1379245020, 
1441582800, 1381753740), class = c("POSIXct", "POSIXt"), tzone = ""), 
    Value = c(40, 65, 44, 65, 44)), .Names = c("y", "Value"), row.names = c(NA, 
-5L), class = "data.frame")
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Using data.table you can join to the nearest value

library(data.table)

x <- as.data.table(x)
y <- data.table(date=y)

res <- x[y, on='date', roll='nearest']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...