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.