Lynda
Lynda

Reputation: 151

How would I inverse the binary digits (0 and 1) of a matrix in R?

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

Answers (5)

akrun
akrun

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

data

set.seed(123) mat <- matrix(sample(0:1, 16, replace = TRUE), 4)

Upvotes: 0

Ape
Ape

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

Cole
Cole

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

Ronak Shah
Ronak Shah

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

T. Ewen
T. Ewen

Reputation: 136

You could try

indOnes <- matrix == 1
indZeros <- matrix == 0
matrix[indOnes] <- 0
matrix[indZeros] <- 1

Upvotes: 0

Related Questions