[R] expand a matrix
Jinsong Zhao
j@zh@o @end|ng |rom ye@h@net
Tue Sep 6 04:45:38 CEST 2022
Hi there,
I have a matrix likes:
> m
[,1] [,2] [,3] [,4]
[1,] NA 1 2 3
[2,] 1 NA 6 5
[3,] 2 6 NA 4
[4,] 3 5 4 NA
I hope to expand it to 10 by 10 matrix, M, likes:
> M
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] NA NA NA NA 1 1 2 3 3 3
[2,] NA NA NA NA 1 1 2 3 3 3
[3,] NA NA NA NA 1 1 2 3 3 3
[4,] NA NA NA NA 1 1 2 3 3 3
[5,] 1 1 1 1 NA NA 6 5 5 5
[6,] 1 1 1 1 NA NA 6 5 5 5
[7,] 2 2 2 2 6 6 NA 4 4 4
[8,] 3 3 3 3 5 5 4 NA NA NA
[9,] 3 3 3 3 5 5 4 NA NA NA
[10,] 3 3 3 3 5 5 4 NA NA NA
I use the following code:
M <- matrix(NA, 10, 10)
for (i in 1:10) {
for (j in 1:10) {
if (i %in% 1:4 & j %in% 5:6) M[i,j] <- M[j,i] <- m[1,2]
if (i %in% 1:4 & j == 7) M[i,j] <- M[j,i] <-m[1,3]
if (i %in% 1:4 & j %in% 8:10) M[i,j] <- M[j,i] <-m[1,4]
if (i %in% 5:6 & j == 7) M[i,j] <- M[j,i] <-m[2,3]
if (i %in% 5:6 & j %in% 8:10) M[i,j] <- M[j,i] <-m[2,4]
if (i == 7 & j %in% 8:10) M[i,j] <- M[j,i] <-m[3,4]
}
}
Is there any convenience way to do it? Thanks!
Best,
Jinsong
More information about the R-help
mailing list