R - Comparing values in a column and creating a new column with the results of this comparison. Is there a better way than looping?

后端 未结 3 1726
余生分开走
余生分开走 2021-01-06 11:41

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

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-06 11:54

    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 NAs 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
    

提交回复
热议问题