Reputation: 151
I have created a matrix of binary digits from reading in a pgm file using the R package pixmap but I am trying to inverse the binary digits (making all 0s become 1s and all 1s become 0s) and outputting the matrix again. Is there an efficient way of doing this?
Upvotes: 3
Views: 2164
Reputation: 887421
We can negate the mat
to return a logical matrix and use +
to coerce it to binary
+!(mat)
# [,1] [,2] [,3] [,4]
#[1,] 1 1 1 0
#[2,] 1 0 1 1
#[3,] 1 0 0 0
#[4,] 0 0 0 1
set.seed(123) mat <- matrix(sample(0:1, 16, replace = TRUE), 4)
Upvotes: 0
Reputation: 1169
You can try abs(1-your_matrix)
mat <- matrix(as.numeric(runif(6) > 0.5), 3, 2)
mat
# [,1] [,2] [,3]
#[1,] 1 0 1
#[2,] 1 0 1
abs(1-mat)
# [,1] [,2] [,3]
#[1,] 0 1 0
#[2,] 0 1 0
Upvotes: 0
Reputation: 11255
matrix <- +(!matrix)
The !
coerces it into a logical matrix and switches the 0s and 1s to TRUE and FALSE. The +
coerces it back to 0s and 1s.
Upvotes: 5
Reputation: 389095
If you have matrix with 1 and 0's and want to change 1's with 0's and vice versa you can do
+(mat == 0)
# [,1] [,2] [,3] [,4]
#[1,] 1 1 1 0
#[2,] 1 0 1 1
#[3,] 1 0 0 0
#[4,] 0 0 0 1
data
where original mat
was :
set.seed(123)
mat <- matrix(sample(0:1, 16, replace = TRUE), 4)
mat
# [,1] [,2] [,3] [,4]
#[1,] 0 0 0 1
#[2,] 0 1 0 0
#[3,] 0 1 1 1
#[4,] 1 1 1 0
Upvotes: 1
Reputation: 136
You could try
indOnes <- matrix == 1
indZeros <- matrix == 0
matrix[indOnes] <- 0
matrix[indZeros] <- 1
Upvotes: 0