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 1754
余生分开走
余生分开走 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 12:15

    You can use a "rolling equality test" with zoo 's rollapply. Also, identical is preferred to ==.

    #identical(NA, NA)
    #[1] TRUE
    #NA == NA
    #[1] NA
    
    library(zoo)
    
    df$mov <- c(rollapply(df$b, width = 2, 
            FUN = function(x) as.numeric(!identical(x[1], x[2]))), "no_comparison")
          #`!` because you want `0` as `TRUE` ;
          #I added a "no_comparison" to last value as it is not compared with any one
    df
    #   a  b           mov
    #1  5  1             0
    #2  1  1             0
    #3  9  1             1
    #4  5 NA             1
    #5  9  1             1
    #.....
    #19 1 NA             0
    #20 1 NA no_comparison
    

提交回复
热议问题