我有NA值的数据帧。我想与以前和NAS后的值之间的顺序替换这些来港定居。
请看下面的例子:
# Example data
df <- data.frame(x1 = c(5, NA, NA, 10, NA),
x2 = c(NA, 2, NA, - 10, NA),
x3 = c(10, NA, 15, NA, 20))
df
# x1 x2 x3
# 5 NA 10
# NA 2 NA
# NA NA 15
# 10 -10 NA
# NA NA 20
两个值之间NAS应该具有序列置换。在开始或结束的NA应保持NA:
# Expected output
# x1 x2 x3
# 5 NA 10
# 6.666667 2 12.5
# 8.333333 -4 15
# 10 -10 17.5
# NA NA 20
我怎么能代替两个值之间的NA以自动化的方式?
在动物园na.approx功能做到这一点插值很容易。
df <- data.frame(x1 = c(5, NA, NA, 10, NA),
x2 = c(NA, 2, NA, - 10, NA),
x3 = c(10, NA, 15, NA, 20))
df
#> x1 x2 x3
#> 1 5 NA 10
#> 2 NA 2 NA
#> 3 NA NA 15
#> 4 10 -10 NA
#> 5 NA NA 20
zoo::na.approx(df)
#> x1 x2 x3
#> [1,] 5.000000 NA 10.0
#> [2,] 6.666667 2 12.5
#> [3,] 8.333333 -4 15.0
#> [4,] 10.000000 -10 17.5
#> [5,] NA NA 20.0
由reprex package(v0.2.0)创建于2019年2月10日。
下面是imputeTS包的溶液:
# Example data
df <- data.frame(x1 = c(5, NA, NA, 10, NA),
x2 = c(NA, 2, NA, - 10, NA),
x3 = c(10, NA, 15, NA, 20))
library("imputeTS")
na.interpolation(df, option = "linear)
对于imputeTS :: na.interpolation您可以选择通过参数选项(选项=“样条曲线”或选项=“斯坦”)不同的插值方法。