Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace 0s in a matrix with a pre-specified value

Tags:

r

matrix

mat <- diag(3)
> mat
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    1    0
[3,]    0    0    1

I have a matrix with 1 along the diagonal and 0 everywhere else. I want to replace the 0s with 0.3, so the matrix looks like

> mat
     [,1] [,2] [,3]
[1,]    1  0.3  0.3
[2,]  0.3    1  0.3
[3,]  0.3  0.3    1

What's a quick way of doing this?

like image 262
Adrian Avatar asked Dec 01 '22 08:12

Adrian


2 Answers

Try this sum

mat + 0.3 * (1 - mat)
##      [,1] [,2] [,3]
## [1,]  1.0  0.3  0.3
## [2,]  0.3  1.0  0.3
## [3,]  0.3  0.3  1.0

A variation of that is to write it as the following convex combination of mat and 1.

0.7 * mat + 0.3
##      [,1] [,2] [,3]
## [1,]  1.0  0.3  0.3
## [2,]  0.3  1.0  0.3
## [3,]  0.3  0.3  1.0
like image 193
G. Grothendieck Avatar answered Dec 03 '22 23:12

G. Grothendieck


We could create a boolean vector that indicates the 0 and assign it each element which is TRUE

mat[mat == 0] <- 0.3
     [,1] [,2] [,3]
[1,]  1.0  0.3  0.3
[2,]  0.3  1.0  0.3
[3,]  0.3  0.3  1.0

G.Grothendieck2 is in front in terms of speed :-) enter image description here

like image 23
TarJae Avatar answered Dec 03 '22 23:12

TarJae