How to fill a matrix with zero (0)

Klausos Klausos picture Klausos Klausos · Jan 19, 2015 · Viewed 82.1k times · Source

I need to fill matrix distances with 0. How can I do this?

distances <- matrix(1:25, nrow=5, ncol=5)
apply(distances, c(1, 2), function(x) 0)

Answer

David Arenburg picture David Arenburg · Jan 19, 2015

I'll just put it here as there are bunch of nice answers in the comments

You could create a whole new matrix using the dimensions of your old matrix

matrix(0L, nrow = dim(distances)[1], ncol = dim(distances)[2])  # @nrussell

Or, similarly, to save a few keystrokes (because a matrix is a special case of two dimensional array)

array(0L, dim(distances)) # @alexis_laz

Or you could preserve the structure of your old matrix using [] and fill it with zeroes

distances[] <- 0L # @Richard            

Or you could simply multiply all the values by zero

distances*0L # @akrun

Or more general solution would be which will take in count NA cases too (because every number in power of zero is always equals to 1)

distances^0L - 1L # @docendodiscimus

Or some of my stuff: You could convert your matrix to a logical matrix in a various ways and then add zeros, for example:

is.na(distances) + 0L # if you don't have `NA` values in your matrix

Or just

(!distances) + 0L # if you don"t have zeroes in your matrix

If you might have zero or NA value in the matrix, row(distances) (or col(distances)) will not:

is.na(row(distances)) + 0L
(!row(distances)) + 0L

And one can force the entire matrix to be NA values, as a way to produce a matrix of 1's, then subtract 1:

is.na(distances + NA) - 1L

Or just for fun

(distances == "Klausos Klausos") + 0L # if you don't have your name as one of the values

Another (a bit awkward) method would be using dim<-

`dim<-`(rep_len(0L, length(distances)), dim(distances))