开发者

replace 0's with 1's and vice versa for a diagonal matrix in R

开发者 https://www.devze.com 2023-01-07 18:52 出处:网络
Can anyone tell me how to replace开发者_如何学运维 0\'s with 1\'s and vice versa for a diagonal matrix in R.If your matrix is mat and you want to flip all 1s as 0s...

Can anyone tell me how to replace开发者_如何学运维 0's with 1's and vice versa for a diagonal matrix in R.


If your matrix is mat and you want to flip all 1s as 0s...

mat <- 1-mat


I don't know anything about R but it seems like you can address a matrix like this:
http://cran.r-project.org/doc/manuals/R-intro.html#Array-indexing

I would suspect you could solve your problem using a for loop:
http://cran.r-project.org/doc/manuals/R-intro.html#Repetitive-execution


Since matrices are stored in mode of numeric, type of integer/double, and storage mode integer/double (assuming that matrix holds numerical values) you can use simple square bracket indexing to address specific values in them, e.g.

# create dummy data
> m <- matrix(rnorm(25), 5)
> mode(m)    # check mode
[1] "numeric"
> typeof(m)  # check type
[1] "double"
> storage.mode(m)
[1] "double"

Now, in order to create diagonal matrix, you can use lower.tri and upper.tri functions, which return logical values for matrix elements beneath and above the main diagonal, respectively.

You can use lower.tri and upper.tri functions to set off-diagonal elements to 0.

> m[lower.tri(m)] <- 0
> m[upper.tri(m)] <- 0
> m
          [,1]       [,2]       [,3]      [,4]      [,5]
[1,] 0.3356640  0.0000000  0.0000000  0.000000 0.0000000
[2,] 0.0000000 -0.2940369  0.0000000  0.000000 0.0000000
[3,] 0.0000000  0.0000000 -0.4490546  0.000000 0.0000000
[4,] 0.0000000  0.0000000  0.0000000 -1.093924 0.0000000
[5,] 0.0000000  0.0000000  0.0000000  0.000000 0.3199157

You can, of course, set any constant to lower/upper diagonal elements, be it numerical, character, logical, NA, etc...

Once you have set zeros as an off-diagonal elements, you can simply use square-bracket indexing. A little diversion: bare in mind that mathematically, vectors are special cases of matrices (and vice versa), but the same doesn't stand for R:

> is.vector(m)
[1] FALSE
> is.matrix(1:10)
[1] FALSE

But, finally, you can do:

> m[m == 0] <- 1

This will insert 1 in matrix wherever zeros occur. You can use diag function to access/change the diagonal elements, for example:

> m[m == 1] <- 0
> diag(m) <- rep(pi, 5)

will change your diagonal matrix to scalar one.

After this boring post of mine, let us all hope that it helped someone, somehow...

Cheers!

0

精彩评论

暂无评论...
验证码 换一张
取 消