I am trying to fill missing data based on whether the previous and last NA value are the same. For example, this is the dummy dataset:
df <- data.frame(ID = c(rep(1, 6), rep(2, 6), rep(3, 6), rep(4, 6), rep(5, 6), rep(6, 6),
rep(7, 6), rep(8, 6), rep(9, 6), rep(10, 6)),
with_missing = c("a", "a", NA, NA, "a", "a",
"a", "a", NA, "b", "b", "b",
"a", NA, NA, NA, "c", "c",
"b", NA, "a", "a", "a", "a",
"a", NA, NA, NA, NA, "a",
"a", "a", NA, "b", "a", "a",
"a", "a", NA, NA, "a", "a",
"a", "a", NA, "b", "b", "b",
"a", NA, NA, NA, "c", "c",
"b", NA, "a", "a", "a", "a"),
desired_result = c("a", "a", "a", "a", "a", "a",
"a", "a", NA, "b", "b", "b",
"a", NA, NA, NA, "c", "c",
"b", NA, "a", "a", "a", "a",
"a", "a", "a", "a", "a", "a",
"a", "b", "b", "b", "a", "a",
"a", "a", "a", "a", "a", "a",
"a", "a", NA, "b", "b", "b",
"a", NA, NA, NA, "c", "c",
"b", NA, "a", "a", "a", "a"))
So if there is a gap of four rows, for example, but the value before and after the gap are the same, then I want the gap to be filled with those same values; whereas if the values before and after the NA are different, I don't want to fill it. In addition, I need to group the data by the ID variable.
I've tried na.locf but I can't work out how to add in the condition of "if they're the same before and after NA".
Thanks.