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
CodePudding user response:
If it's for the sake of brevity, you could define apply an anonymous function in your pipeline like so:
matrix(c(1,2,3,4,3,9,5,5,8),ncol=3) %>%
(\(.) {.[upper.tri(.) | lower.tri(.)] = 999; .})() %>%
## rest of pipeline
Edit
shamelessly stealing borrowing from @Maël 's elegant solution:
matrix(c(1,2,3,4,3,9,5,5,8),ncol=3) %>%
ifelse(row(.) == col(.), ., 999) %>%
## rest of pipeline
(note: does not work with the native pipe operator |>
)
CodePudding user response:
With ifelse
:
ifelse(row(m) == col(m), m, 999)
CodePudding user response:
We may use
matrix(c(1,2,3,4,3,9,5,5,8),ncol=3) %>%
`[<-`(upper.tri(.) | lower.tri(.), 999)
-output
[,1] [,2] [,3]
[1,] 1 999 999
[2,] 999 3 999
[3,] 999 999 8