Replace all values in a matrix <0.1 with 0 Replace all values in a matrix <0.1 with 0 r r

Replace all values in a matrix <0.1 with 0


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.


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


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 <- 0X[X < minvalue] <- minvalue

For Dataframe or Matrix.

minvalue <- 0n <- 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))