[英]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
.我有一个对称矩阵m1
,我想根据m1
中的值和位置创建第二个矩阵m2
。
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".如果值在 position(x1-3 和 y4-5)或(x4-5 和 y1-3)中,并且如果值本身 >2,则为“A”,否则如果它在这些位置但 <3,则“B”,否则如果是 (x1-3 和 y1-3) 或 (x4-5 和 y4-5) 且 >2 则为“C”,否则为“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.无论position如何,我都可以对所有值使用m2 <- ifelse(m1 >2, "A", "B")
,但我对如何仅针对某些位置执行此操作感到困惑。 I've also tried things like m1[1:3,4:5]
as nested if statements but couldn't get it to work.我也尝试过像m1[1:3,4:5]
这样的嵌套 if 语句,但无法让它工作。
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.