conditional replacement of matrix values

I have a matrix in which I want to replace some values if they meet a condition.

#example matrix
data <- c(1:10, 1:3, 1:4, 1:10, 1:3, 1:10)
mymatrix <- matrix(data, nrow = 10, ncol = 4)

I want to replace the matrix value with 0 if it is the same as the value to the left (by row). Example:

so mymatrix[3,2]==mymatrix[3,1], thus I I would like to replace mymatrix[3,2] with 0. I want to check all values in the matrix by row for this.

I am looking for something like.. if(mymatrix[x,y]==mymatrix[x,y-1]) { 0}, but cannot find something that works

I assumed you wanted the first column to stay the same. Here's my solution:

data <- c(1:10, 1:3, 1:4, 1:10, 1:3, 1:10)
mymatrix <- matrix(data, nrow = 10, ncol = 4)

#Replace the matrix value with 0 if it is the same as the value to the left (by row). 

newmatrix <- mymatrix

for (i in 2:(ncol(mymatrix))){
   newmatrix[mymatrix[, i]  == mymatrix[, i-1], i] <- 0
}

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
newmatrix
#>       [,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 (v1.0.0)

1 Like

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)