【问题标题】:Replace NAs between Values with Sequence用序列替换值之间的 NA
【发布时间】:2019-02-09 22:01:24
【问题描述】:

我有一个带有 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?

【问题讨论】:

    标签: r dataframe na missing-data


    【解决方案1】:

    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 年 2 月 10 日创建。

    【讨论】:

      【解决方案2】:

      这是一个带有 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")选择不同的插值方法。

      【讨论】:

      • 感谢您的替代解决方案!
      猜你喜欢
      • 2022-06-16
      • 1970-01-01
      • 2021-10-11
      • 2020-11-22
      • 1970-01-01
      • 2016-02-07
      • 2019-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多