user3570187 - 4 months ago 36

R Question

I want to create a minimum value which compares the lower and upper triangular matrix of a matrix. For example

`A = matrix( c(2, 4, 3, 1, 5, 7,4,2,4), nrow=3, ncol=3,byrow = TRUE)`

B= matrix(c(0,1,3,1,0,2,3,2,0), nrow=3, ncol=3,byrow= TRUE)

I would like to create a matrix like this with diagonal elements set to 0 and the rest to be minimum of upper and lower elements. For example (A(1,2), A(2,1)) which is min(4,1) =1. This results in matrix B. Can anyone suggest how to achieve this manipulation?

Answer

I think you want to use `pmin`

:

```
A <- matrix( c(2, 4, 3, 1, 5, 7,4,2,4), nrow=3, ncol=3,byrow = TRUE)
diag(A) <- 0
output <- pmin(A, t(A))
output
[,1] [,2] [,3]
[1,] 0 1 3
[2,] 1 0 2
[3,] 3 2 0
```