datetimes1
は不定期のdatetimesであり、datetimes2
は定期的なdatetimesです。 datetimes1
には、最初の表に示すように、5:10などの欠落した日時があります。私が欲しいもの定期的な日時スケジュールに不規則な日付時刻を合わせる
は、各datetimes1
がdatetimes2
に近いものであり、全てのdatetimes1
が上品正しい行になるように、datetimes2
にdatetimes1
を一致させようとすることです。
最初に、datetimes1
を最も近い5分に丸めて、datetimes2
に一致させようとしましたが、一部の日付は3分ずれているので、間違った値に丸められます。私が試した
次のものがdatetimes1
がdatetimes2
に正確に等しいである見つけ、0からtolerance
を設定することで、最初のものをdatetimes1
datetimes2
に一致するようにし、その後、すべてのループで1によってtolerance
を増やし始める、とされていないdatetimes1
と一致datetimes2
に一致しており、指定されたtolerance
によってオフになっています。
この方法の問題は、5:33と5:37の両方が5:35から2分ずれているため、5:33が最初に5:35に一致してから5:37が含まれないことですテーブル。与えられたコードを使って得られた結果については、2番目の表を参照してください。
この問題をどのように解決できるかご存知ですか?
私が見たい:
datetimes1 datetimes2
1 2014-07-24 05:05:00 2014-07-24 05:05:00
2 <NA> 2014-07-24 05:10:00
3 2014-07-24 05:15:00 2014-07-24 05:15:00
4 2014-07-24 05:23:00 2014-07-24 05:20:00
5 2014-07-24 05:27:00 2014-07-24 05:25:00
6 2014-07-24 05:33:00 2014-07-24 05:30:00
7 2014-07-24 05:37:00 2014-07-24 05:35:00
8 2014-07-24 05:41:00 2014-07-24 05:40:00
9 2014-07-24 05:45:00 2014-07-24 05:45:00
しかし、私はこの代わりました:ここ
datetimes1 datetimes2
1 2014-07-24 05:05:00 2014-07-24 05:05:00
2 <NA> 2014-07-24 05:10:00
3 2014-07-24 05:15:00 2014-07-24 05:15:00
4 <NA> 2014-07-24 05:20:00
5 2014-07-24 05:23:00 2014-07-24 05:25:00
6 2014-07-24 05:27:00 2014-07-24 05:30:00
7 2014-07-24 05:33:00 2014-07-24 05:35:00
8 2014-07-24 05:41:00 2014-07-24 05:40:00
9 2014-07-24 05:45:00 2014-07-24 05:45:00
は私のコードは次のとおりです。
irregulars <- c("2014-07-24 05:05",
"2014-07-24 05:15",
"2014-07-24 05:23",
"2014-07-24 05:27",
"2014-07-24 05:33",
"2014-07-24 05:37",
"2014-07-24 05:41",
"2014-07-24 05:45")
df1 <- data.frame(datetimes <- as.POSIXct(irregulars, "GMT"))
regulars <- c("2014-07-24 05:05",
"2014-07-24 05:10",
"2014-07-24 05:15",
"2014-07-24 05:20",
"2014-07-24 05:25",
"2014-07-24 05:30",
"2014-07-24 05:35",
"2014-07-24 05:40",
"2014-07-24 05:45")
df2 <- setNames(data.frame(matrix(NA,length(regulars),2)),c("datetimes1","datetimes2"))
df2$datetimes2 <- as.POSIXct(regulars, "GMT")
# Match irregulars to regulars
for(tolerance in c(0:3)) {
for(idx in which(!df1$datetimes %in% df2$datetimes1)) {
dt <- abs(difftime(df2$datetimes2, df1$datetimes[idx], "GMT", "mins"))
dt.min <- min(dt[is.na(df2$datetimes1)])
if (dt.min > tolerance) next
idx2 <- which(dt == dt.min)
df2$datetimes1[idx2] <- df1$datetimes[idx]
}
}
df2$datetimes1 <- as.POSIXct(df2$datetimes1, "GMT", origin = "1970-01-01 00:00:00")