Increase matrix proportionally in R

I have a matrix of 2 rows and 2 columns and you want to increase this matrix so that it has 4 rows and 4 columns with the same values ​​in it. As if to "scale" the matrix.

This is my 2 * 2 matrix:

a<-matrix(1:4,nrow=2,byrow=TRUE)

     [,1] [,2]
[1,]    1    2
[2,]    3    4

And I want to transform this matrix so that it looks like this:

     [,1] [,2] [,3] [,4]
[1,]    1    1    2    2
[2,]    1    1    2    2
[3,]    3    3    4    4
[4,]    3    3    4    4

I simplified the problem: the values ​​in the matrix just serve as an example. The true matrix I want to convert is 10 rows and columns and should be converted to 30 rows and 30 columns, but the principle should be the same.
I am going to solve this problem with a loop, but I'm sure there should be a more elegant way.

+4
source share
1 answer

Kronecker

enlarge <- function(m, k) kronecker(m, matrix(1, k, k))
enlarge(a, 2)
#      [,1] [,2] [,3] [,4]
# [1,]    1    1    2    2
# [2,]    1    1    2    2
# [3,]    3    3    4    4
# [4,]    3    3    4    4
enlarge(a, 3)
#      [,1] [,2] [,3] [,4] [,5] [,6]
# [1,]    1    1    1    2    2    2
# [2,]    1    1    1    2    2    2
# [3,]    1    1    1    2    2    2
# [4,]    3    3    3    4    4    4
# [5,]    3    3    3    4    4    4
# [6,]    3    3    3    4    4    4
+10

Source: https://habr.com/ru/post/1629799/


All Articles