In R, how to add TRUE / FALSE column if a value differs from previous or following value?
r
Solution
You can apply `diff` to see if two entries are the same. You want two of these diffs, to see if both entries around an element are the same:
> !(c(NA, diff(as.numeric(x$status))) | c(rev(diff(as.numeric(rev(x$status)))), NA))
[1] NA TRUE FALSE FALSE FALSE TRUE NA
The first expression tells whether the prior element is different:
> c(NA, diff(as.numeric(x$status)))
[1] NA 0 0 -1 1 0 0
The second tells whether the following element is different:
> c(rev(diff(as.numeric(rev(x$status)))), NA)
[1] 0 0 1 -1 0 0 NA
The "or" operation `|` returns `TRUE` for nonzero, which means a leading or following element is different, so we then invert the result with the leading `!`.
Problem
Sample data: ``` df <- data.frame( time = c(1, 2, 3, 4, 5, 6, 7), status = c("good", "good", "good", "bad", "good", "good", "good") ) ``` Output: ``` time status 1 1 good 2 2 good 3 3 good 4 4 bad 5 5 good 6 6 good 7 7 good ``` I would like to add a new column `statuschange` IF `status` differs from the row above or below. The output would look like this: ``` time status statuschange 1 1 good NA 2 2 good TRUE 3 3 good FALSE 4 4 bad FALSE 5 5 good FALSE 6 6 good TRUE 7 7 good NA ``` I have the sense that are lots of ways to do this, but I haven't been able to figure it out. Any assistance is appreciated!