Flagging system: Check for changing values in a data frame I've written the following code to check if a value in a data frame changes. I'm looking at the last 5 values. If there was no change at all I want my code to return 1, if a single one (or multiple) of the last 5 are different to the value that is being checked return 0. Finally I want the returned values in a new column in my data frame.

Here's my code so far. It works but I think there is a nicer (and more clean) way to do it.

mydata &lt;- data.frame("id" = 1:100, "ta" = c(sample(x = c(-5:20), size = 94, replace = T), rep(1,6))) # include a repetition to check if code works
nums &lt;- mydata$id # create a dummy for iteration
qc_dummy &lt;- vector(mode = "list", length = length(nums)) # create a dummy vector for the values computed in the for loop

for(i in 1:length(nums)) {
  qc_dummy[[i]] &lt;- ifelse(mydata[nums[i], 2] - mydata[nums[i-1], 2] == 0, 
                          ifelse(mydata[nums[i], 2] - mydata[nums[i-2], 2] == 0,
                                 ifelse(mydata[nums[i], 2] - mydata[nums[i-3], 2] == 0,
                                        ifelse(mydata[nums[i], 2] - mydata[nums[i-4], 2] == 0,
                                               ifelse(mydata[nums[i], 2] - mydata[nums[i-5], 2] == 0, 1, 0) ,0), 0) ,0) ,0) 
}
mydata$qc1 &lt;- as.vector(c(0,unlist(qc_dummy))) # first value of list is skipped by unlist (logi(0)) -&gt; add 0
I reduced the example data, for easier viewing

# new example data:
mydata &lt;- data.frame(ta = 1:13)
mydata[2:3, 1] &lt;- 1L
mydata[6:12, 1] &lt;- 2L

n &lt;- 3 # how many equal values we need

require(data.table)
setDT(mydata) # convert to data.table
mydata
mydata[, mathcPrev := fifelse((ta - shift(ta, 1)) == 0L, T, F, F)]
mydata[, g := cumsum(!mathcPrev)] # grouping value, if value has changed
mydata[, count := cumsum(mathcPrev), by = g]
mydata[, qc2 := fifelse(count &gt;= n, 1L, 0L)]
mydata
#     ta mathcPrev g count qc2
#  1:  1     FALSE 1     0   0
#  2:  1      TRUE 1     1   0
#  3:  1      TRUE 1     2   0
#  4:  4     FALSE 2     0   0
#  5:  5     FALSE 3     0   0
#  6:  2     FALSE 4     0   0
#  7:  2      TRUE 4     1   0
#  8:  2      TRUE 4     2   0
#  9:  2      TRUE 4     3   1
# 10:  2      TRUE 4     4   1
# 11:  2      TRUE 4     5   1
# 12:  2      TRUE 4     6   1
# 13: 13     FALSE 5     0   0


So, the idea is to create index mathcPrev, that shows if this value matches previous, and then we can count how many equal values we have in a row.