Insert a row at a specific location in a matrix using R

I am trying to add rows to a matrix in certain places where the locations are in the vector. The diagram below shows the inputs and expected results. I tried using the for loop, but couldn't get it to work. Any suggestions help.

Source Matrix (6x3)

(1) 1   2   3
(2) 4   5   6
(3) 7   8   9
(4) 6   9   2
(5) 3   6   1
(6) 2   2   7

Location vector (indicates the row in the source matrix that will contain zeros)

[2, 5, 6]  

Matrix of results (6 + length.vector x 3)

(1) 1   2   3
(2*)0   0   0
(3) 4   5   6
(4) 7   8   9
(5*)0   0   0
(6*)0   0   0
(7) 6   9   2
(8) 3   6   1
(9) 2   2   7
+4
source share
3 answers

Here is one approach:

## inputs
m <- matrix(c(1,2,3,4,5,6,7,8,9,6,9,2,3,6,1,2,2,7),ncol=3L,byrow=T);
i <- c(2L,5L,6L);

## solution
ris <- integer(nrow(m)+length(i)); ris[i] <- nrow(m)+1L; ris[-i] <- seq_len(nrow(m));
rbind(m,0)[ris,];
##       [,1] [,2] [,3]
##  [1,]    1    2    3
##  [2,]    0    0    0
##  [3,]    4    5    6
##  [4,]    7    8    9
##  [5,]    0    0    0
##  [6,]    0    0    0
##  [7,]    6    9    2
##  [8,]    3    6    1
##  [9,]    2    2    7

, ris. , nrow(m) , length(i). , nrow(m)+1L, seq_len(nrow(m)). , ris , , ( ).

+3
mat <- matrix(1:18,6)
vec <- c(2, 5, 6)

# New matrix 'new_mat' with all zeros, 
# No. of rows = original matrix rows + number new rows to be added
new_mat <- matrix(0,nrow=9,ncol=3)  

# 'new_mat' rows getting filled with `mat` values
new_mat[-vec,] <- mat   
new_mat
#      [,1] [,2] [,3]
# [1,]    1    7   13
# [2,]    0    0    0
# [3,]    2    8   14
# [4,]    3    9   15
# [5,]    0    0    0
# [6,]    0    0    0
# [7,]    4   10   16
# [8,]    5   11   17
# [9,]    6   12   18
+2

This is similar to @bgoldst's answer, a little different. It adds a string of zeros and then reorders the strings. We start with the nrow(m) + 1length vector nrow(m) + length(x)(where xis the location vector), and then replace the indices that are not in x, with their corresponding source indices.

nr <- nrow(m)
rbind(m, 0)[replace(rep(nr + 1L, nr + length(x)), -x, seq_len(nr)), ]
#      [,1] [,2] [,3]
# [1,]    1    2    3
# [2,]    0    0    0
# [3,]    4    5    6
# [4,]    7    8    9
# [5,]    0    0    0
# [6,]    0    0    0
# [7,]    6    9    2
# [8,]    3    6    1
# [9,]    2    2    7

Data:

m <- structure(c(1L, 4L, 7L, 6L, 3L, 2L, 2L, 5L, 8L, 9L, 6L, 2L, 3L, 
6L, 9L, 2L, 1L, 7L), .Dim = c(6L, 3L))
x <- c(2, 5, 6)
+1
source

All Articles