Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replacing off-diagonal elements with a fixed value

I have a square matrix and now I want to replace all its off-diagonal elements with a fixed value. Some approaches how this can be done are discussed in Replacing non-diagonal elements in a matrix in R (hopefully a better asked this time)

For example,

m <- matrix(c(1,2,3,4,3,9,5,5,8),ncol=3)
m[upper.tri(m) | lower.tri(m)] <- 999
m

I am wondering if the step can be performed using dplyr chain rule, something like

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

library(dplyr)
matrix(c(1,2,3,4,3,9,5,5,8),ncol=3) %>%
 ### add this -> m[upper.tri(m) | lower.tri(m)] <- 999

Any pointer will be very helpful

>Solution :

You can use the mutate function in dplyr to modify the elements of the matrix. Here is an example of how you can do this:

library(dplyr)

m <- matrix(c(1,2,3,4,3,9,5,5,8), ncol = 3)

m %>%
  mutate(m = ifelse(upper.tri(m) | lower.tri(m), 999, m))

This will create a new matrix with the same dimensions as m but with the off-diagonal elements replaced by 999.

Alternatively, you can use the replace function to directly modify the original matrix m:

m[upper.tri(m) | lower.tri(m)] <- 999

This will modify the original matrix m in place and replace the off-diagonal elements with 999.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading