Counting the number of times the next element in a vector is different from the previous

I have a matrix that looks like this:

a=c(rep(0,5),rep(1,5),rep(2,5))
b=c(rep(1,5),rep(1,5),rep(2,5))
d=rbind(a,b)

  [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15]
a    0    0    0    0    0    1    1    1    1     1     2     2     2     2     2
b    1    1    1    1    1    1    1    1    1     1     2     2     2     2     2

What I want to do is count the number of times a value in a row changes. For example, in the first row there are 2 changes in columns 5 through 6 and in columns 10-11.

I used an instruction ifand a loop forto compare each value and a counter cto count the number of times the change occurred:

m=matrix(NA, nrow = length(d[,1]), ncol = 1)

for (s in 1:length(d[,1])){

  c=0

  for (i in 1:length(d[1,])){

    if (i < length(d[1,])){

      if (d[s,i]!=d[s,(i+1)]){
        c=c+1
      }  

    }

  }

  m[s,1]<-c
}

At the end, I have a matrix m with the number of switches on each row. However, my data contains thousands of rows and thousands of columns, and this script takes too much time to count the changes.

+4
source share
3

:

apply(d,1,function(x) length(rle(x)$values)-1)

d. apply, () 1, , ( ).

, length(rle(x)$values) , x. help(rle), rle() :

, . , rle(x)$values. , , , , " ". , length(), . , , , , 1 , length().

, .

+5

diff

rowSums(t(apply(d,1,diff)))

, ( , , t rowSums)

colSums(apply(d,1,diff))

, "1" . , ,

colSums(apply(d,1,diff)!=0)
+6

data.table ( - ):

# Your original data
a=c(rep(0,5),rep(1,5),rep(2,5))
b=c(rep(1,5),rep(1,5),rep(2,5))
d=rbind(a,b)

# Solution starts here...
library(data.table)
dt <- as.data.table(d)  # convert to data.table for high performance. "Performance penalty" here is that the matrix is copied completely (setDT does not work on a matrix)
cols <- ncol(dt)
diff <- dt[, 1:(cols-1), with=FALSE ] != dt[, 2:cols, with=FALSE ]  # find differences (TRUE/FALSE table as result)
rowSums(diff)       # sum the differences per row

[1] 2 1

:

, "" , TRUE/FALSE, TRUE :

> diff
        V1    V2    V3    V4    V5    V6    V7    V8    V9  V10   V11   V12   V13   V14
[1,] FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE
[2,] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE

. TRUE ( 1 R, FALSE 0, as.numeric(TRUE)).

PS: , ( d; -)

+2

All Articles