I would use a user-defined function to do this. Note that if three consecutive columns have the same value, only the second one will have its value set to 0 because when the code gets to the third one, the value in the second one will have been change already.
data <- c(1:10, 1:3, 1:4, 1:10, 1:3, 1:10)
mymatrix <- matrix(data, nrow = 10, ncol = 4)
mymatrix
#> [,1] [,2] [,3] [,4]
#> [1,] 1 1 4 1
#> [2,] 2 2 5 2
#> [3,] 3 3 6 3
#> [4,] 4 1 7 4
#> [5,] 5 2 8 5
#> [6,] 6 3 9 6
#> [7,] 7 4 10 7
#> [8,] 8 1 1 8
#> [9,] 9 2 2 9
#> [10,] 10 3 3 10
mymatrix[,2]
#> [1] 1 2 3 1 2 3 4 1 2 3
myfunc <- function(M) {
for (i in 2:ncol(M)){
M[, i] <- ifelse(M[ ,i] == M[,i-1], 0, M[ ,i])
}
return(M)
}
mymatrix2 <- myfunc(mymatrix)
mymatrix2
#> [,1] [,2] [,3] [,4]
#> [1,] 1 0 4 1
#> [2,] 2 0 5 2
#> [3,] 3 0 6 3
#> [4,] 4 1 7 4
#> [5,] 5 2 8 5
#> [6,] 6 3 9 6
#> [7,] 7 4 10 7
#> [8,] 8 1 0 8
#> [9,] 9 2 0 9
#> [10,] 10 3 0 10
Created on 2021-02-17 by the reprex package (v0.3.0)