用序列替换值之间的NA

时间:2019-02-09 22:01:25

标签: r dataframe na missing-data

我有一个带有NA值的数据框。我想用NA前后的值之间的顺序替换这些NA。

考虑以下示例:

# 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

两个值之间的NA应替换为一个序列。开头或结尾的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?

2 个答案:

答案 0 :(得分:2)

zoo中的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-02-10创建。

答案 1 :(得分:1)

这是带有 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,您可以通过参数选项(option =“ spline”或option =“ stine”)选择其他插值方法。