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
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.