Search code examples
rmatchrowapply

check changes in consecutive elements (i.e columns) by row ignoring NAs in a data frame


I´m trying to check if the elements in a given row are different.

As example,

> s <- as.data.frame(matrix(ncol=10, nrow=3, 
+                            c(0,NA,NA,1,1,NA,0,NA,NA,NA,NA,NA,0,NA,0,0,NA,NA,0,0,NA,NA,0,0,0,1,1,NA,NA,NA), byrow = TRUE))

> s
  V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1  0 NA NA  1  1 NA  0 NA NA  NA
2 NA NA  0 NA  0  0 NA NA  0   0
3 NA NA  0  0  0  1  1 NA NA  NA

This is my data frame and I would like to see if there are any changes from "0" to "1" in consecutive columns by row ignoring NA values. The output should be for example a vector v <-c("TRUE","FALSE","TRUE") for the given example. Is there any simple solution?


Solution

  • In case you actually care about whether the sequence 0:1 is present, not just whether there's a non-zero difference, you can do

    library(zoo)
    apply(s, 1, function(x) 'TRUE' %in% rollapply(x[!is.na(x)], 2, all.equal, 0:1, 
                                                  check.attributes = F))
    #[1]  TRUE FALSE  TRUE
    

    To illustrate what I mean:

    s[2,5] <- -1
    apply(s, 1, function(x) any(diff(x[!is.na(x)]) != 0)) # Rui
    # [1] TRUE TRUE TRUE
    apply(s, 1, function(x) 'TRUE' %in% rollapply(x[!is.na(x)], 2, all.equal, 0:1, 
                                                  check.attributes = F))
    # [1]  TRUE FALSE  TRUE