I have the following dataframe:
day <- c(1,2,3,4,5,6,7,8,9, 10, 11)
totalItems <- c(700, NA, 32013, NA, NA, NA, 39599, NA, NA, NA, 107542)
df <- data.frame(day, totalItems)
I need to create another variable/column where NAs are replaced by the outcome of a formula: (following available non NA - previous available non NA) / (row number of following non NA - row number of previous non NA), in order to get this final dataframe :
day <- c(1,2,3,4,5,6,7,8,9, 10, 11)
totalItems <- c(700, NA, 32013, NA, NA, NA, 39599, NA, NA, NA, 107542)
estimatedDaily <- c(700, 15656, 15656, 1897, 1897, 1897, 1897, 16986, 16986, 16986, 16986)
df.new <- data.frame(day, totalItems, estimatedDaily)
I tried to juggle with tidyr::replace_na()
but I couldn't figure out how to define the formula to be able to identify the previous and the following available non NA.
Many thanks in advance for helping.
question from:
https://stackoverflow.com/questions/65650171/fill-in-na-by-outcome-of-formula-between-previous-and-following-non-na-values-in