flamenco
flamenco

Reputation: 2840

Map a matrix into a logical matrix

Looking for an elegant way to map a matrix into a logical matrix. For example, if n[i,j] >= 10 it should mapped into 1, else 0.

 12 34 3 4 10
 11 1  3 4 6
 2  34 4 3 22

should be mapped in:

1 1 0 0 1
1 0 0 0 0
0 1 0 0 1

Upvotes: 0

Views: 72

Answers (3)

akrun
akrun

Reputation: 887078

If x is the matrix

(x>=10)*1
 #      [,1] [,2] [,3] [,4] [,5]
 #[1,]    1    1    0    0    1
 #[2,]    1    0    0    0    0
 #[3,]    0    1    0    0    1

Or

(x>=10)+0    

Upvotes: 3

IRTFM
IRTFM

Reputation: 263332

This should be as simple as:

 mat <- your.mat >= 10
 mat[] <- as.numeric( mat ) # the `[]` on the LHS preserves the structure.

E.g.

> mat <-  matrix(sample(1:20,16),4) >5 
> mat[] <- as.numeric(mat)
> mat
     [,1] [,2] [,3] [,4]
[1,]    1    0    0    1
[2,]    1    1    1    1
[3,]    1    0    1    1
[4,]    1    1    0    1

Upvotes: 1

user3710546
user3710546

Reputation:

With ifelse:

x <- matrix(c(12, 34, 3, 4, 10, 11, 1,  3, 4, 6, 2,  34, 4, 3, 22), 3, 5, byrow=TRUE)
ifelse(x >= 10, 1, 0)
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    0    0    1
[2,]    1    0    0    0    0
[3,]    0    1    0    0    1

Upvotes: 1

Related Questions