[R] expand a matrix

Deepayan Sarkar deep@y@n@@@rk@r @end|ng |rom gm@||@com
Tue Sep 6 08:30:00 CEST 2022


On Tue, Sep 6, 2022 at 8:16 AM Jinsong Zhao <jszhao using yeah.net> wrote:
>
> 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!

Assuming I understand what you are trying to do, perhaps

i <- rep(1:4, c(4, 2, 1, 3))
m[i, i]

Like most operations in R, indexing is vectorized.

Best,
-Deepayan


> Best,
> Jinsong
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list