Say I have this matrices:
emp <- matrix(nrow = 13, ncol = 13)
emp2 <- matrix(nrow = 13, ncol = 13)
emp[lower.tri(emp)] <- 2
emp2[lower.tri(emp)] <- 3
And I want to combine them so below the diagonal, I have all values = 2 and above all values = 3. I have managed to produce this as such (then the result is just the emp matrix).
emp[upper.tri(emp)] <- t(emp2[lower.tri(emp2)])
However, now I would like to store the result and make a function for this (after all the matrices I want to use are inside elements of a list). Do you know how can I store this in a new matrix? Or perhaps a better alternative.
I hope I have provided a reproducible enough example, otherwise, let me know.
Thank you!
I think you can use pmax
with option na.rm = TRUE
> pmax(emp, t(emp2), na.rm = TRUE)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13]
[1,] NA 3 3 3 3 3 3 3 3 3 3 3 3
[2,] 2 NA 3 3 3 3 3 3 3 3 3 3 3
[3,] 2 2 NA 3 3 3 3 3 3 3 3 3 3
[4,] 2 2 2 NA 3 3 3 3 3 3 3 3 3
[5,] 2 2 2 2 NA 3 3 3 3 3 3 3 3
[6,] 2 2 2 2 2 NA 3 3 3 3 3 3 3
[7,] 2 2 2 2 2 2 NA 3 3 3 3 3 3
[8,] 2 2 2 2 2 2 2 NA 3 3 3 3 3
[9,] 2 2 2 2 2 2 2 2 NA 3 3 3 3
[10,] 2 2 2 2 2 2 2 2 2 NA 3 3 3
[11,] 2 2 2 2 2 2 2 2 2 2 NA 3 3
[12,] 2 2 2 2 2 2 2 2 2 2 2 NA 3
[13,] 2 2 2 2 2 2 2 2 2 2 2 2 NA