Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding row and column to matrix at the same time

I want to add a column with values [1, 1, 0] to a matrix with dim (2×2) and a row with values [1, 1, 0] to produce a matrix with dim (3×3).

# Create the original matrix
original_matrix <- matrix(c(7, 2, 3, 5), nrow = 2)

# Add a column with values [1, 1, 0]
modified_matrix <- cbind(original_matrix, c(1, 1, 0))

# Add a row with values [1, 1, 0]
final_matrix <- rbind(modified_matrix, c(1, 1, 0))

I used the cbind function to add columns and the rbind function to add rows. Is there any way to do it in one go?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can avoid creating modified_matrix by doing this:

final_matrix <- rbind(cbind(original_matrix, c(1, 1)), c(1, 1, 0))

But if you want the answer in a general case you’ll have to manually "cut" one of your vectors.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading