To understand and create a matrix in R, read this shot.
The cbind()
function adds additional columns to a matrix in R.
cbind(matrix, c(column elements))
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.The cbind()
function returns a modified matrix with a new column.
# creating a matrix myMatrix <- matrix(c("apple", "banana", "cherry", "orange","grape", "pineapple", "pear", "melon", "fig"), nrow = 3, ncol = 3) # adding a colum using the cbind() function myNewMatrix <- cbind(myMatrix, c("lemon", "mango", "strawberry")) # printing the new matrid myNewMatrix
3
by 3
matrix (a matrix with 3 rows and 3 columns) myMatrix
using the matrix()
function. We then passing the parameter values of its shape. nrow = 3
represents 3 rows, and ncol = 3
represents 3 columns.cbind()
function to add a new column of elements to the existing matrix.myNewMatrix
.It is worth noting that the new column must be the same length as the current matrix.
RELATED TAGS
CONTRIBUTOR
View all Courses