我查看了一些网页(但它们的结果不符合我的需求):
我想编写一个函数,可以实现以下功能:
假设有一个向量a
。
a = c(100000, 137862, NA, NA, NA, 178337, NA, NA, NA, NA, NA, 295530)
首先,在单个和连续的NA
之前和之后找到数值。
在这种情况下是 137862, NA, NA, NA, 178337
和 178337, NA, NA, NA, NA, NA, 295530
。
其次,计算每个部分的斜率,然后替换NA
。
# 137862, NA, NA, NA, 178337
slope_1 = (178337 - 137862)/4
137862 + slope_1*1 # 1st NA replace with 147980.8
137862 + slope_1*2 # 2nd NA replace with 158099.5
137862 + slope_1*3 # 3rd NA replace with 168218.2
# 178337, NA, NA, NA, NA, NA, 295530
slope_2 = (295530 - 178337)/6
178337 + slope_2*1 # 4th NA replace with 197869.2
178337 + slope_2*2 # 5th NA replace with 217401.3
178337 + slope_2*3 # 6th NA replace with 236933.5
178337 + slope_2*4 # 7th NA replace with 256465.7
178337 + slope_2*5 # 8th NA replace with 275997.8
最后,期望的向量应该是这个:
a_without_NA = c(100000, 137862, 147980.8, 158099.5, 168218.2, 178337, 197869.2, 217401.3,
236933.5, 256465.7, 275997.8, 295530)
如果开头是单个或连续的NA,则会被保留。
# NA at begining
b = c(NA, NA, 1, 3, NA, 5, 7)
# 3, NA, 5
slope_1 = (5-3)/2
3 + slope_1*1 # 3rd NA replace with 4
b_without_NA = c(NA, NA, 1, 3, 4, 5, 7)
# NA at ending
c = c(1, 3, NA, 5, 7, NA, NA)
# 3, NA, 5
slope_1 = (5-3)/2
3 + slope_1*1 # 1st NA replace with 4
c_without_NA = c(1, 3, 4, 5, 7, NA, NA)
注意:在我的实际情况中,向量的每个元素都是递增的(
vector[n + 1] > vector[n]
)。我知道原理,但不知道如何编写自定义函数来实现此目的。
非常感谢任何帮助!