Reputation: 11
I have two matrices, matrix A and matrix B (5 x 5). I randomly assigned values between 0 and 4 to matrix A.
Now, for example, I want to check if A[1,2] > A[2,1]. If that holds true I want to assign a specific value to B[1,2] and B[2,1]. In this case it should be B[1,2] = 3 and B[2,1] = 0. If A[1,2] < A[2,1] it should be the other way around; e.g. B[1,2] = 0 and B[2,1] = 3. If A[1,2] == A[2,1] it should be B[1,2] = 1 and B[2,1] = 1.
I am looking for an R code to do this as a loop to fill matrix B completely with the right values of either 0,1 or 3.
I would really appreciate any help! Thank you very much in advance!
If the outcome of R is matrix A, matrix B should look like the self-drawn matrix.
Upvotes: 1
Views: 141
Reputation: 101209
We can do like this
> `diag<-`(3 * (A > t(A)) + 1 * (A == t(A)), NA)
[,1] [,2] [,3]
[1,] NA 3 0
[2,] 0 NA 1
[3,] 3 1 NA
Upvotes: 1