Reputation: 10051
Given a sample data as follows:
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")
Let's say I need to interplote NA
s in value1
and value2
but only if date
is in the date range of date>='2021-10-16' & date<='2021-10-20'
.
I used this code but it was apply to the whole column value1
.
library(zoo)
df$value1 <- na.approx(df$value1)
How could I achieve that based on code above? Thanks.
Upvotes: 0
Views: 56
Reputation: 51592
You can filter your period and loop over the columns applying the function, i.e.
sapply(df[-1], function(i)zoo::na.approx(i[df$date>='2021-10-16' & df$date<='2021-10-20']))
Upvotes: 1