Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing diagonal elements using dplyr pipe

Tags:

r

dplyr

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
like image 329
rm167 Avatar asked Nov 11 '20 12:11

rm167


Video Answer


2 Answers

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
like image 162
tmfmnk Avatar answered Oct 16 '22 17:10

tmfmnk


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
like image 31
akrun Avatar answered Oct 16 '22 16:10

akrun