使用 R 根据另一列的条件插入某些列的 NA

Interpolate certain columns' NAs based on the condition of another column using R

给定一个样本数据如下:

df <- structure(list(date = structure(c(18912, 18913, 18914, 18915, 
18916, 18917, 18918, 18919, 18920, 18921, 18922, 18923), class = "Date"), 
    value1 = c(1.115668, NA, 
    1.093685, NA, 1.072135, 1.06152, 1.05101, NA, NA, 1.0201, 
    1.01, 1), value2 = c(1.015, 1.030225, NA, NA, 1.077284, 1.093443, 
    1.109845, 1.126493, NA, NA, NA, 1.195618
    )), row.names = c(NA, -12L), class = "data.frame")

假设我需要在 value1value2 中插入 NAs,但前提是 datedate>='2021-10-16' & date<='2021-10-20' 的日期范围内。

我使用了这段代码,但它适用于整个专栏 value1

library(zoo)
df$value1 <- na.approx(df$value1)

我如何根据上面的代码实现它?谢谢。

您可以过滤句点并循环应用该函数的列,即

sapply(df[-1], function(i)zoo::na.approx(i[df$date>='2021-10-16' & df$date<='2021-10-20']))