# Ensuring non-decreasing lagged differences

In the data example below, the cumulative values (cumvals) should ideally be non-decreasing (equivalently the consecutive differences (diffs) must be non-negative). However, in some instances, that's not the case due to revisions that result to data updates at a later date. When such revisions are made, changes need to be made so that the cumulative values are monotonically non-decreasing. I've attempted fixing this issue for a while without success.

``````cumvals <- c(0, 0, 1, 0, 1, 1, 2, 5, 7, 7, 6, 5, 8, 8, 7)
ID <- rep(1001, length(cumvals))
df <- data.frame(ID, cumvals)
df%>%
mutate(diffs= c(0, diff(cumvals)))
``````

The corrected values should be as in the data frame below.

Ideally, if the trend for cumvals decreases from say day 3 to day 4, we want to keep the smaller value for day 4 and modify the value for day 1 to equal to that for day 2 and preserve the non-decreasing aspect. Now, if the value for days 2 and 3 are similar, then we have a decrease at day 4, we need to modify the values for days 2 and 3 and assign them to value for day 4. The last scenario is when their are consecutive decreases. For example, when we have consecutive instances of `7, 7, 6, 5`, we want modify this to `5, 5, 5, 5`. That way the vector/sequence is non-decreasing.

``````corrcumvals <- c(0, 0, 0, 0, 1, 1, 2, 5, 5, 5, 5, 5, 7, 7, 7)
df2 <- data.frame(ID, cumvals, corrcumvals)
df2%>%
mutate(diffs= c(0, diff(cumvals)), corrdiffs= c(0, diff(corrcumvals)))

``````

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.