Reverse/backward na.approx

Reverse/backward na.approx

我有一个带前导 NA 的日期向量,我想使用包 zoo 中的 na.approx 为这些 NA 生成一个近似序列。

na.approx 不适用于前导 NA:

x <- as.Date(c(rep(NA,3),"1992-01-16","1992-04-16","1992-07-16",
"1992-10-16","1993-01-15","1993-04-16","1993-07-17"))
as.Date(na.approx(x,na.rm=FALSE))

[1] NA           NA           NA           "1992-01-16" "1992-04-16" 
1992-07-16" "1992-10-16" "1993-01-15" "1993-04-16" "1993-07-17"

我认为我可以使用 rev 反转我的矢量,但我仍然得到 NAs

as.Date(na.approx(rev(x),na.rm=FALSE))

 [1] "1993-07-17" "1993-04-16" "1993-01-15" "1992-10-16" "1992-07-16" 
"1992-04-16" "1992-01-16" NA           NA           NA   

有什么想法吗?

找到我的答案。 na.spline 处理大量数据做得很好。在上面的例子中,我有几个日期导致近似值漂移。但是,在我的真实例子中,没有漂移。

as.Date(na.spline(x,na.rm=FALSE))
 [1] "1993-07-17" "1993-04-16" "1993-01-15" "1992-10-16" "1992-07-16" 
"1992-04-16" "1992-01-16" "1991-10-15" "1991-07-13" "1991-04-06"

na.approx 需要为 minmax 值以外的值传递 rule 你的载体。如果使用 rule=2,则用最接近的值估算缺失值。

as.Date(na.approx(x,na.rm=FALSE, rule=2))
# [1] "1992-01-16" "1992-01-16" "1992-01-16" "1992-01-16" "1992-04-16" "1992-07-16" "1992-10-16" "1993-01-15"
#  [9] "1993-04-16" "1993-07-17"

作为替代方案,您可以使用 na.spline(如您的回答)。你提到它会变得有点疯狂 因此您可以编写一个函数来根据测量之间的时间差来估算值。 我这里用第一个非遗漏差

add_leading_seq_dates <- function(x) {
        first_non_missing = which.min(is.na(x))
        first_day_diff = na.omit(diff(x))[1]
        no_of_leadng_missing = first_non_missing - 1
        input_dates = x[first_non_missing] - cumsum(rep(first_day_diff, no_of_leadng_missing)) 
        x[is.na(x)] = rev(input_dates)
        x
}

add_leading_seq_dates(x)

# [1] "1991-04-18" "1991-07-18" "1991-10-17" "1992-01-16" "1992-04-16"
# [6] "1992-07-16" "1992-10-16" "1993-01-15" "1993-04-16" "1993-07-17"

diff(add_leading_seq_dates(x))
# Time differences in days
# [1] 91 91 91 91 91 92 91 91 92