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?
>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.