Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert row at a specific location in matrix using R

Tags:

r

matrix

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
like image 997
Fernando DePaolis Avatar asked Jun 04 '16 01:06

Fernando DePaolis


People also ask

How do I add a specific row in R?

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.

How do I add a row to an existing matrix in R?

The rbind() function adds additional row(s) to a matrix in R.

How do I select a row from 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.

How do you add a row and column name to a matrix in R?

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().


1 Answers

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
like image 143
Sowmya S. Manian Avatar answered Sep 21 '22 11:09

Sowmya S. Manian