I want to replace the diagonal elements of a matrix in the middle of a piping process but can't figure out a way to do this. I know I can replace the diagonal elements this using diag()
function, but I just don't know how to use diag()
function inside a piping process. Sample data is given below and I want the following steps put together in a piping process. Thanks in advance.
aa <- matrix(1:25, nrow =5)
diag(aa) <- NA
One option could be:
aa %>%
`diag<-`(., NA)
[,1] [,2] [,3] [,4] [,5]
[1,] NA 6 11 16 21
[2,] 2 NA 12 17 22
[3,] 3 8 NA 18 23
[4,] 4 9 14 NA 24
[5,] 5 10 15 20 NA
We could use replace
with a logical condition
library(dplyr)
aa %>%
replace(., col(.) == row(.), NA)
-output
# [,1] [,2] [,3] [,4] [,5]
#[1,] NA 6 11 16 21
#[2,] 2 NA 12 17 22
#[3,] 3 8 NA 18 23
#[4,] 4 9 14 NA 24
#[5,] 5 10 15 20 NA
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With