简体   繁体   中英

R: assigning values to a new matrix based on value and coordinate in another matrix

I have a symmetrical matrix m1 and I would like to create a second matrix m2 depending on the value and the location in m1 .

For example (apologies for the poor pseudocode):

> m1
      [,1] [,2] [,3] [,4] [,5]
[1,]    0    1    2    3    4
[2,]    1    0    5    6    7
[3,]    2    5    0    8    1
[4,]    3    6    8    0    9
[5,]    4    7    1    9    0

If the value is in position (x1-3 and y4-5) or (x4-5 and y1-3), and if the value itself is >2, then "A", else if it's in those positions but <3 then "B", else if it's (x1-3 and y1-3) or (x4-5 and y4-5) and >2 then "C", else "D". And if possible to ignore the diagonal.

So that:

> m2
      [,1] [,2] [,3] [,4] [,5]
[1,]    NA   D    D    A    A
[2,]    D    NA   C    A    A
[3,]    D    C    NA   A    B
[4,]    A    A    A    NA   C
[5,]    A    A    B    C    NA

I can use m2 <- ifelse(m1 >2, "A", "B") for all values regardless of position, but I'm stumped for how to do it just for certain positions. I've also tried things like m1[1:3,4:5] as nested if statements but couldn't get it to work.

You can try the code below

idxc <- col(m1)
idxr <- row(m1)
msk <- idxr %in% 1:3 & idxc %in% 1:3 | idxr %in% 4:5 & idxc %in% 4:5
m1[msk] <- ifelse(m1>2,"C","D")[msk]
m1[!msk] <- ifelse(m1>2,"A","B")[!msk]
m2 <- `diag<-`(m1,NA)

which gives

> m2
     [,1] [,2] [,3] [,4] [,5]
[1,] NA   "D"  "D"  "A"  "A" 
[2,] "D"  NA   "C"  "A"  "A" 
[3,] "D"  "C"  NA   "A"  "B" 
[4,] "A"  "A"  "A"  NA   "C" 
[5,] "A"  "A"  "B"  "C"  NA 

Data

> dput(m1)
structure(c(0L, 1L, 2L, 3L, 4L, 1L, 0L, 5L, 6L, 7L, 2L, 5L, 0L, 
8L, 1L, 3L, 6L, 8L, 0L, 9L, 4L, 7L, 1L, 9L, 0L), .Dim = c(5L, 
5L))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM