I am attempting to carry non-missing observations forward and populate the next two missing observations (although I imagine a solution to this problem would be broadly applicable to carrying observations forward through n rows...).
In the example data frame below I would like to carry forward (propagate) the flag_a
and flag_b
values for each id
for two rows. Here is an example of my data with the desired output included:
id <- c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2)
flag_a <- as.numeric(c(NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA))
flag_b <- as.numeric(c(NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA))
flag_a_desired_output <- as.numeric(c(NA, NA, 1, 1, 1, NA, NA, NA, NA, NA, NA, 1, 1, 1, NA, NA, NA, NA))
flag_b_desired_output <- as.numeric(c(NA, NA, NA, 1, 1, 1, NA, NA, NA, NA, NA, NA, NA, 1, 1, 1, NA, NA))
data <- data.frame(cbind(id, flag_a, flag_b, flag_a_desired_output, flag_b_desired_output))
I have attempted to use the following last observation carried forward (LOCF) function; however, as expected it populates all missing rows rather than just the next two.
na.locf.na <- function(x, na.rm = FALSE, ...) na.locf(x, na.rm = na.rm, ...)
data <- transform(data, flag_a_locf = ave(flag_a, id, FUN = na.locf.na))
data <- transform(data, flag_b_locf = ave(flag_b, id, FUN = na.locf.na))
Any thoughts on how to go about this would be greatly appreciated.
See Question&Answers more detail:
os