Use max for each matrix element

> x <- array(-10:10, dim=c(4,5)) > x [,1] [,2] [,3] [,4] [,5] [1,] -10 -6 -2 2 6 [2,] -9 -5 -1 3 7 [3,] -8 -4 0 4 8 [4,] -7 -3 1 5 9 

How to apply "max (x, 0)" to each element to get this matrix:

  [,1] [,2] [,3] [,4] [,5] [1,] 0 0 0 2 6 [2,] 0 0 0 3 7 [3,] 0 0 0 4 8 [4,] 0 0 1 5 9 
+7
source share
2 answers

Use pmax :

 pmax(x,0) # [,1] [,2] [,3] [,4] [,5] #[1,] 0 0 0 2 6 #[2,] 0 0 0 3 7 #[3,] 0 0 0 4 8 #[4,] 0 0 1 5 9 
+14
source

You can use the index function R [ for this:

 x <- array(-10:10, dim=c(4,5)) x[x < 0] <- 0 

This works because x < 0 produces the output of the logical matrix:

 x < 0 [,1] [,2] [,3] [,4] [,5] [1,] TRUE TRUE TRUE FALSE FALSE [2,] TRUE TRUE TRUE FALSE FALSE [3,] TRUE TRUE FALSE FALSE FALSE [4,] TRUE TRUE FALSE FALSE FALSE 

And the resulting matrix:

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

The time between the two methods is surprisingly similar. Here's a larger example illustrating comparable timings:

 xbigC <- xbigE <- matrix(sample(-100:100, 1e8, TRUE), ncol = 1e4) system.time(xbigC[xbigC < 0] <- 0) #--- user system elapsed 4.56 0.37 4.93 system.time(xbigE <- pmax(xbigE,0)) #--- user system elapsed 4.10 0.51 4.62 all.equal(xbigC, xbigE) #--- [1] TRUE 
+5
source

All Articles