I have a matrix A which is:
A <- matrix(c(1:15), byrow=T, nrow=5)
A
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
[4,] 10 11 12
[5,] 13 14 15
Now I want to create a matrix B, which is 8×8 dimensions (or 10×10, or 15×15, etc), which would look like this:
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 1 2 3 0 0 0 0 0
[2,] 4 5 6 0 0 0 0 0
[3,] 7 8 9 0 0 0 0 0
[4,] 10 11 12 0 0 0 0 0
[5,] 13 14 15 0 0 0 0 0
[6,] 0 0 0 0 0 0 0 0
[7,] 0 0 0 0 0 0 0 0
[8,] 0 0 0 0 0 0 0 0
So starting from A, I want to add columns and rows, to an 8×8 dimensions, all replaced with zero values…
Any idea?
Thank you in advance!!
Try this assuming
Ahas at least one row and one column:or as a single statement:
If
Acan have zero rows or zero columns then useseq_len(nrow(A))andseq_len(ncol(A))in place of1:nrow(A)and1:ncol(A).Alternately, this works even in the case that A has zero rows or columns:
or
or