I would like to impute missing values using the last observation carried forward(locf) or the next observation carried backward(nocb) in two or more gaps.
In order to determine the direction (top/down) to fill the missing values, the first column (Interval) in the data frame is weighted. Interpolation (locf/nocb) should be from the smallest-value end(Interval values that correspond to NAs rows outward). The default fillna is locf.
Example: logic for exceptional nafill : in ID2 column, row 5-7 (header included), the direction will be nocb because (Interval[7,] value= 50) which is less than Interval[5,] value=100.
An attempt using df1 <-df %>%fill(ID1, ID2, ID3,which.min(Interval)) %>% #default direction down
fill(ID1, ID2, ID3, .direction = "up",which.min(Interval))
aint working, please assist to correct it or suggest another efficient R solution. Thank you in advance for your help.
Input
df = data.frame(
Interval = c(0,20,80,100,50,50,130,100,70,80,200),
ID1 = c(0,1,1,0,NA,NA,NA,NA,1,NA,1),
ID2 = c(1,0,0,NA,NA,NA,1,1,3,NA,1),
ID3 = c(1,NA,1,0,3,NA,NA,NA,1,NA,1)
)
Interval ID1 ID2 ID3
0 0 1 1
20 1 0 NA
80 1 0 1
100 0 NA 0
50 NA NA 3
50 NA NA NA
130 NA 1 NA
100 NA 1 NA
70 1 3 1
80 NA NA NA
200 1 1 1
Expected output
Interval ID1 ID2 ID3
0 0 1 1
20 1 0 NA
80 1 0 1
100 0 1 0
50 0 1 3
50 0 1 3
130 0 1 3
100 0 1 3
70 1 3 1
80 NA NA NA
200 1 1 1