I'm trying to add rows to a matrix at particular locations, where the locations are contained in a vector. The schema below shows the inputs and the expected outcome. I tried to use a "for" loop but couldn't make it 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
Vector of locations (indicates the row in the source matrix that will contain zeros)
[2, 5, 6]
Result Matrix(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
To add row to R Data Frame, append the list or vector representing the row, to the end of the data frame. nrow(df) returns the number of rows in data frame. nrow(df) + 1 means the next row after the end of data frame. Assign the new row to this row position in the data frame.
The rbind() function adds additional row(s) to a matrix in R.
Similar to vectors, you can use the square brackets [ ] to select one or multiple elements from a matrix. Whereas vectors have one dimension, matrices have two dimensions. You should therefore use a comma to separate the rows you want to select from the columns.
The rbind() function in the R programming language conveniently adds the names of the vectors to the rows of the matrix. You name the values in a vector, and you can do something very similar with rows and columns in a matrix. For that, you have the functions rownames() and colnames().
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With