I\'m a beginner of R. Although I have read a lot in manuals and here at this board, I have to ask my first question. It\'s a little bit the same as here but not really the s
There are a couple things to consider in your example.
First, to avoid a loop, you can create a copy of the vector that is shifted by one position. (There are about 20 ways to do this.) Then when you test vector B
vs C
it will do element-by-element comparison of each position vs its neighbor.
Second, equality comparisons don't work with NA -- they always return NA. So NA == NA
is not TRUE
it is NA
! Again, there are about 20 ways to get around this, but here I have just replaced all the NA
s in the temporary vector with a placeholder that will work for the tests of equality.
Finally, you have to decide what you want to do with the last value (which doesn't have a neighbor). Here I have put 1
, which is your assignment for "doesn't match its neighbor".
So, depending on the range of values possible in b
, you could do
c = df$b
z = length(c)
c[is.na(c)] = 'x' # replace NA with value that will allow equality test
df$mov = c(1 * !(c[1:z-1] == c[2:z]),1) # add 1 to the end for the last value