Shawn Brar
Shawn Brar

Reputation: 1420

Set values withing a range equal to 1 and rest to 0

I have a 7000 X 7000 matrix in R. For example purpose I will use a smaller matrix as following:-

a <- matrix(c(0:-9, 1:-8, 2:-7, 3:-6, 4:-5, 5:-4, 6:-3, 7:-2, 8:-1, 9:0),
            byrow = TRUE, ncol = 10, nrow = 10)

I want to create a new matrix which has values equal to 1 where the absolute values in matrix a are between the closed interval of 2 and 5. And rest all other values equal to zero.

This would make the following matrix:-

b <- matrix(c(0,0,1,1,1,1,0,0,0,0
              0,0,0,1,1,1,1,0,0,0
              1,0,0,0,1,1,1,1,0,0
              1,1,0,0,0,1,1,1,1,0
              1,1,1,0,0,0,1,1,1,1
              1,1,1,1,0,0,0,1,1,1
              0,1,1,1,1,0,0,0,1,1
              0,0,1,1,1,1,0,0,0,1
              0,0,0,1,1,1,1,0,0,0
              0,0,0,0,1,1,1,1,0,0),
            byrow = TRUE, ncol = 10, nrow = 10)

I can do this using for loop, but I just want to know if there is a much better and effcient solution to do this.

Thanks in advance.

Upvotes: 2

Views: 58

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 102221

Perhaps you can try

> +((abs(a) - 2) * (abs(a) - 5) <= 0)
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    0    0    1    1    1    1    0    0    0     0
 [2,]    0    0    0    1    1    1    1    0    0     0
 [3,]    1    0    0    0    1    1    1    1    0     0
 [4,]    1    1    0    0    0    1    1    1    1     0
 [5,]    1    1    1    0    0    0    1    1    1     1
 [6,]    1    1    1    1    0    0    0    1    1     1
 [7,]    0    1    1    1    1    0    0    0    1     1
 [8,]    0    0    1    1    1    1    0    0    0     1
 [9,]    0    0    0    1    1    1    1    0    0     0
[10,]    0    0    0    0    1    1    1    1    0     0

Upvotes: 0

Roland
Roland

Reputation: 132854

You can just write down the comparison. It gives you a logical matrix and you can then use unary + to turn the result into an integer matrix.

+(abs(a) >= 2 & abs(a) <= 5)

#      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,]    0    0    1    1    1    1    0    0    0     0
# [2,]    0    0    0    1    1    1    1    0    0     0
# [3,]    1    0    0    0    1    1    1    1    0     0
# [4,]    1    1    0    0    0    1    1    1    1     0
# [5,]    1    1    1    0    0    0    1    1    1     1
# [6,]    1    1    1    1    0    0    0    1    1     1
# [7,]    0    1    1    1    1    0    0    0    1     1
# [8,]    0    0    1    1    1    1    0    0    0     1
# [9,]    0    0    0    1    1    1    1    0    0     0
#[10,]    0    0    0    0    1    1    1    1    0     0

Upvotes: 2

Related Questions