How to add a column to a matrix in R
Overview
To understand and create a matrix in R, read this shot.
Adding a column to a matrix
The cbind() function adds additional columns to a matrix in R.
Syntax
cbind(matrix, c(column elements))
Parameter value
The cbind() function takes two parameter values:
matrix: This is the existing matrix to which we will add a column.column elements: This is the list of elements we wish to add to the new column.
Return value
The cbind() function returns a modified matrix with a new column.
Code
# creating a matrixmyMatrix <- matrix(c("apple", "banana", "cherry", "orange","grape", "pineapple", "pear", "melon", "fig"), nrow = 3, ncol = 3)# adding a colum using the cbind() functionmyNewMatrix <- cbind(myMatrix, c("lemon", "mango", "strawberry"))# printing the new matridmyNewMatrix
Code explanation
- Line 2: We create a
3by3matrix (a matrix with 3 rows and 3 columns)myMatrixusing thematrix()function. We then passing the parameter values of its shape.nrow = 3represents 3 rows, andncol = 3represents 3 columns. - Line 5: We use the
cbind()function to add a new column of elements to the existing matrix. - Line 7: We print
myNewMatrix.
It is worth noting that the new column must be the same length as the current matrix.