Tyrone Williams
Tyrone Williams

Reputation: 77

converting to rectangular matrix to a square matrix in r

I have a rectangular matrix ( 4 rows, 16 columns) , I am trying to convert this into a square (16 rows x 16 columns) , the extra unrelated rows should be padded with zeros.

From

  0 1 2 3 4 5 11 12 13 14 15 63 64 65 66 67
0 0 1 1 1 1 1  0  0  0  0  0  0  0  0  0  0
1 1 0 1 0 1 1  0  0  0  0  1  0  0  0  0  0
2 1 0 0 0 0 0  1  1  1  1  0  0  0  0  0  0
3 0 0 0 0 0 0  0  0  0  0  0  1  1  1  1  1

To

   0 1 2 3 4 5 11 12 13 14 15 63 64 65 66 67
 0 0 1 1 1 1 1  0  0  0  0  0  0  0  0  0  0
 1 1 0 1 0 1 1  0  0  0  0  1  0  0  0  0  0
 2 1 0 0 0 0 0  1  1  1  1  0  0  0  0  0  0
 3 0 0 0 0 0 0  0  0  0  0  0  1  1  1  1  1
 4 0 0 0 0 0 0  0  0  0  0  0  0  0  0  0  0
 5 0 0 0 0 0 0  0  0  0  0  0  0  0  0  0  0
11 0 0 0 0 0 0  0  0  0  0  0  0  0  0  0  0
12 0 0 0 0 0 0  0  0  0  0  0  0  0  0  0  0
13 0 0 0 0 0 0  0  0  0  0  0  0  0  0  0  0
14 0 0 0 0 0 0  0  0  0  0  0  0  0  0  0  0
15 0 0 0 0 0 0  0  0  0  0  0  0  0  0  0  0
63 0 0 0 0 0 0  0  0  0  0  0  0  0  0  0  0
64 0 0 0 0 0 0  0  0  0  0  0  0  0  0  0  0
65 0 0 0 0 0 0  0  0  0  0  0  0  0  0  0  0
66 0 0 0 0 0 0  0  0  0  0  0  0  0  0  0  0
67 0 0 0 0 0 0  0  0  0  0  0  0  0  0  0  0

Any advise on how to do this in r will be very helpful.

Upvotes: 1

Views: 2878

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99331

You can add the necessary rows by using the dimensions of the original matrix

d <- dim(x)
cn <- colnames(x)
rbind(x, matrix(0, diff(d), ncol(x), dimnames = list(cn[(d[1]+1):d[2]])))

where x is

x <- 
structure(c(0L, 1L, 1L, 0L, 1L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 1L, 
0L, 0L, 0L, 1L, 1L, 0L, 0L, 1L, 1L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 
0L, 1L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 1L, 0L, 0L, 1L, 0L, 0L, 0L, 
0L, 0L, 1L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 1L, 0L, 
0L, 0L, 1L), .Dim = c(4L, 16L), .Dimnames = list(c("0", "1", 
"2", "3"), c("0", "1", "2", "3", "4", "5", "11", "12", "13", 
"14", "15", "63", "64", "65", "66", "67")))

Upvotes: 2

Related Questions