How to convert negative values in a matrix to 0 in R?


To convert negative values in a matrix to 0, we can use pmax function. For example, if we have a matrix called M that contains some negative and some positive and zero values then the negative values in M can be converted to 0 by using the command pmax(M,0).

Example

Consider the below data frame −

 Live Demo

M1<-matrix(sample(-10:2,40,replace=TRUE),ncol=2)
M1

Output

      [,1] [,2]
[1,]   0    -2
[2,]  -1    0
[3,]  -10   1
[4,]  -4   -8
[5,]  -7   -8
[6,]   0    0
[7,]  -7    0
[8,]  -8   -3
[9,]  -1   -9
[10,] -4   -10
[11,]  1    -7
[12,]  0    -5
[13,] -6    -3
[14,] -4    -4
[15,] -4    -4
[16,]  0     2
[17,] -7    -2
[18,] -7    -2
[19,] -5    -5
[20,] -6    -7

Converting negative values in matrix M1 to 0 −

Example

pmax(M1,0)

Output

     [,1] [,2]
[1,]  0    0
[2,]  0    0
[3,]  0    1
[4,]  0    0
[5,]  0    0
[6,]  0    0
[7,]  0    0
[8,]  0    0
[9,]  0    0
[10,] 0    0
[11,] 1    0
[12,] 0    0
[13,] 0    0
[14,] 0    0
[15,] 0    0
[16,] 0    2
[17,] 0    0
[18,] 0    0
[19,] 0    0
[20,] 0    0

Example

 Live Demo

M2<-matrix(sample(-10:10,80,replace=TRUE),ncol=4)
M2

Output

      [,1] [,2] [,3] [,4]
[1,]  -10   1    4    7
[2,]  -9    5    6    2
[3,]   7    4    1   -5
[4,]   2    9    0    2
[5,]  -2   -6    1   -9
[6,]   8   -9   -9    1
[7,]   3   -3    0   -1
[8,]   5    0   -3    5
[9,]  -2    5    7   -5
[10,] -3    0   -8    1
[11,] -4    3   -2   -4
[12,] 5     4   -5    2
[13,] 0    10   -1   -8
[14,] 5    -9   -4   -1
[15,] 6   -6     2    0
[16,] -6  -9    -5   -8
[17,] -4   4   -9    -3
[18,] 4  -10    4     7
[19,] -9  -8    2    -4
[20,] -2   3    9    -8

Converting negative values in matrix M2 to 0 −

Example

pmax(M2,0)

Output

      [,1] [,2] [,3] [,4]
[1,]   0    1    4    7
[2,]   0    5    6    2
[3,]   7    4    1    0
[4,]   2    9    0    2
[5,]   0    0    1    0
[6,]   8    0    0    1
[7,]   3    0    0    0
[8,]   5    0    0    5
[9,]   0    5    7    0
[10,] 0     0    0    1
[11,] 0    3     0    0
[12,] 5    4     0    2
[13,] 0   10     0    0
[14,] 5    0     0    0
[15,] 6    0     2    0
[16,] 0    0     0    0
[17,] 0    4     0    0
[18,] 4    0     4    7
[19,] 0    0     2    0
[20,] 0    3     9    0

Updated on: 16-Mar-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements