Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

matrix
r
add
row
communitycreator

How to add a row to a matrix in R

Onyejiaku Theophilus Chidalu

Overview

To understand and create a matrix in R, click on this shot.

Adding a row to a matrix

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

Syntax

rbind(matrix, c(row elements))

Parameter value

The rbind() function takes two parameter values:

  1. matrix: This is an already existing matrix to which we wish to add a column.
  2. row elements: This is the list of elements we wish to add to the new row.

Return value

The rbind() function returns a modified matrix with a new column.

Code

# creating a matrix
myMatrix <- matrix(c("apple", "banana", "cherry", "orange","grape", "pineapple", "pear", "melon", "fig"), nrow = 3, ncol = 3)

# adding a row using the rbind() function
myNewMatrix <- rbind(myMatrix, c("lemon", "mango", "strawberry"))

# printing the new matrid
myNewMatrix
Adding a row to a matrix using the rbind() function

Code explanation

  • Line 2: We create a 3 by 3 matrix (a matrix with 3 rows and 3 columns) myMatrix using the matrix() function. We pass the parameter values of its shape. nrow = 3 represents 3 rows, and ncol = 3 represents 3 columns.
  • Line 5: Using the rbind() function, we add a row of elements to the existing matrix.
  • Line 7: We print myNewMatrix.

It is worth noting that the new row we wish to add must be the same length as the current matrix.

RELATED TAGS

matrix
r
add
row
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring