Replace all values in a matrix <0.1 with 0

Solution 1:

X[X < .1] <- 0

(or NA, although 0 sounds more appropriate in this case.)

Matrices are just vectors with dimensions, so you can treat them like a vector when you assign to them. In this case, you're creating a boolean vector over X that indicates the small values, and it assigns the right-hand-side to each element that's TRUE.

Solution 2:

ifelse should work:

mat <- matrix(runif(100),ncol=5)
mat <- ifelse(mat<0.1,NA,mat)

But I would choose Harlan's answer over mine.

mat[mat < 0.1] <- NA

Solution 3:

I think you will find that 'ifelse' is not a vector operation (its actually performing as a loop), and so it is orders of magnitudes slower than the vector equivalent. R favors vector operations, which is why apply, mapply, sapply are lightning fast for certain calculations.

Small Datasets, not a problem, but if you have an array of length 100k or more, you can go and cook a roast dinner before it finishes under any method involving a loop.

The below code should work.

For vector

minvalue <- 0
X[X < minvalue] <- minvalue

For Dataframe or Matrix.

minvalue <- 0
n <- 10 #change to whatever.
columns <- c(1:n)
X[X[,columns] < minvalue,columns] <- minvalue

Another fast method, via pmax and pmin functions, this caps entries between 0 and 1 and you can put a matrix or dataframe as the first argument no problems.

ulbound <- function(v,MAX=1,MIN=0) pmin(MAX,pmax(MIN,v))

Solution 4:

Just to provide an (in my opinion) interesting alternative:

If you need to clamp the values so they are never smaller than a value, you could use pmax:

set.seed(42)
m <- matrix(rnorm(100),10)

m <- pmax(m, 0) # clamp negative values to 0

...This doesn't quite work in your case though since you want values < 0.1 to become 0.